Server File Download, Server File Download to local
Basic Steps for downloading files:
1. Get the download link and create a response to send the request. (use an asynchronous request to avoid blocking the main thread because the file has been downloaded for a long time ).
2. when a response is received, create a file in the downloaded directory. use NSFileHandle to create a file for internal processing. (check whether the file exists-use NSFileManager to create the file-NSFileHandle's fileHandleForWritingAtPath method to write the file ).
3. When receiving data, write the data received in segments to the file.
4. Disable NSFileHandle after receiving the file.
The above is a normal download step, and no code demonstration is required here. The following uses the resumable download function as an example.
Because the sandbox path is often used in this program, a method to obtain the sandbox path is provided first.
-(NSString *)getFilePath{ NSString *document=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *filePath=[document stringByAppendingPathComponent:_fileName]; return filePath;}
Download event
-(IBAction) download :( UIButton *) sender {// obtain the video Address URL NSString * string = @ "http: // 221.228.249.8/2/B/k/h/o/bkhoxvtmbviswrdeddgvxcbufzwvwb/empty "; // separate the addresses and store them in an array, get the file name NSArray * array = [string componentsSeparatedByString: @ "/"]; _ fileName = [array lastObject]; // transcode the url (the address cannot be identified when there is a man in it and must be converted to a compliant format) string = [string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString: string]; // variable response, because the location of the resumable download re-sending request is different from the previous NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // determine whether data has been downloaded before (whether data exists in the sandbox) if ([[NSFileManager defaultManager] fileExistsAtPath: [self getFilePath]) // previously downloaded {// obtain the information of the previously downloaded file // The information of the dictionary saved file (reported by the server) NSDictionary * fileDic = [[NSFileManager defaultManager] attributesOfItemAtPath: [self getFilePath] error: nil]; NSLog (@ "% @", fileDic); // obtain the acceptable file size _ accepted icesize = [fileDic [NSFileSize] longLongValue]; // bytes = 0-499 content of the first 500 bytes of the Request // bytes = 500-content of the Second 500 bytes of the Request // bytes = 500-1000 content of a range in the request Resource // bytes = 0-1,499-500 NSString * bytes = [NSString stringWithFormat: @ "bytes = % lld-", _ receiviceSize]; // set the Range of the request Header [request setValue: bytes forHTTPHeaderField: @ "Range"];} _ connection = [NSURLConnection connectionWithRequest: request delegate: self];}
Pause an event
-(IBAction) pause :( UIButton *) sender {// cancel the request link [_ connection cancel]; _ connection = nil ;}
# Pragma mark --- NSURLConnectionDatasource ---
// Response-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {// to obtain the StatusCode status code in response, convert response to NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response; // The remaining file size NSDictionary * responseHead = httpResponse. allHeaderFields; // received file + remaining file = total file size _ totalSize = _ receiviceSize + [responseHead [@ "Content-Length"] longLongValue]; NSFileManager * manager = [NSFileManager defaultManager]; // create a file if the file does not exist in the sandbox if ([manager fileExistsAtPath: [self getFilePath] = NO) {[manager createFileAtPath: [self getFilePath] contents: nil attributes: nil];} _ fileHandle = [NSFileHandle fileHandleForWritingAtPath: [self getFilePath];} // receive data-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {// position the cursor at the end of the file and write the file at the last position each time (the file is written in the file header by default) [_ fileHandle seekToEndOfFile]; [_ fileHandle writeData: data]; // update the file length in real time _ Your icesize = _ Your icesize + data. length;} // received-(void) connectionDidFinishLoading :( NSURLConnection *) connection {[_ fileHandle closeFile];
}