Nsurlsession download file location

Nsurlsession download file location

nsurlsession download file location

Like NSURLConnection, NSURLSession refers to a group of interdependent classes, in addition to finishes with a temporary file path for the downloaded file​. As an extra, in the following code I add a folder called "MyFolder" inside the documents directory path to which I move the file. class. URLSessionDownloadTask: Use this task to download a file from a remote service to a temporary file location. URLSession Task Types.

Nsurlsession download file location - cleared

Use NSURLSession To Implement Download Task Break Point Continue Example

In recent project, i encounter some problems of downloading large file&#;s break point continuation. This article will summarize different download methods and point out the advantage and disadvantage of each method.

1. Direct Download With NSData.

[NSData dataWithContentsOfURL:URL];

The disadvantage of this method is obvious, one is blocking the current thread, the other is that as long as the download fails, the data will not be saved, which is obviously not suitable for large file download.

2. Use NSURLSession&#;s NSURLSessionDownloadTask Method.

To use this method, you need implement below method of NSURLSessionDownloadDelegate.

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { }

But this method also has below drawbacks:

  1. File is downloaded into temp folder, as long as it is not handled in time, it will be deleted by the system,.
  2. When downloading multiple files at the same time, there will be confusion, even if you manually move the downloaded files from temp folder to cache folder, there will be various problems such as file name duplication.

3. Use AFNetworking.

It is also a layer of encapsulation based on task. The specific task still needs to be operated manually by itself, and can not achieve the unified management of break point continuation and network requests. That is, the following methods.

[manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { }];

From this method, we can see that AFN is still based on NSURLSession Download Task packaging, and it is not as good as expected.

4. Download Code Improvement.

To solve above problem, i made an improvement, that is, using NSURLSessionDataTask to send get requests directly to achieve the download of breakpoint continuity, and support multi-file download.

  1. Since use NSURLSession to send network requests, then we can lazily load a session in a utility class. - (NSURLSession *)session { if (!_session) { _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]]; } return _session; }
  2. When you have a session, you also need to have a task, which is also lazy loading. Of course, NSURLDataTask is used here. - (NSURLSessionDataTask *)dataTask { if (!_dataTask) { NSError *error = nil; NSInteger alreadyDownloadLength = XHRAlreadyDownloadLength; //Download has completed. if ([taniaarraindegia.esy.esataLengthDictionary[taniaarraindegia.esy.esme]integerValue] && [taniaarraindegia.esy.esataLengthDictionary[taniaarraindegia.esy.esme] integerValue] == XHRAlreadyDownloadLength) { !taniaarraindegia.esy.esteBlock?:taniaarraindegia.esy.esteBlock(XHRFilePath,nil); return nil; } //If an existing file is larger than the target, that means the download file is executed incorrectly. Delete the file and download again else if ([taniaarraindegia.esy.esataLengthDictionary[taniaarraindegia.esy.esme] integerValue] < XHRAlreadyDownloadLength) { [[NSFileManager defaultManager]removeItemAtPath:XHRFilePath error:&error]; if (!error) { alreadyDownloadLength = 0; } else { NSLog(@"Creation task failed. Please restart"); return nil; } } //The downloaded file size is less than the total file size. Continue the download operation // Create mutableRequest Object NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:taniaarraindegia.esy.esing]]; // Set request header //Range:bytes=xxx-xxx [mutableRequest setValue:[NSString stringWithFormat:@"bytes=%ld-",alreadyDownloadLength] forHTTPHeaderField:@"Range"]; _dataTask = [taniaarraindegia.esy.esn dataTaskWithRequest:mutableRequest]; } return _dataTask; }
  3. We have operate follow check in above task method, 1. Check whether the download is complete or not. If the download complete, call the completed block directly. 2. Check whether the locally stored file is larger than the target file or not. If it is larger than the target file, it means that the file has errors and the old file must be deleted and downloaded again. 3. Continue downloading while the download do not complete.
  4. Key parameters : 1. The total length of the file is the unique key that is stored in the dictionary and written to the sandbox after MD5 encryption through the url address after the first response is received by the server. 2. Get the currently downloaded file size from the NSFileManager and file name. [[[NSFileManager defaultManager]attributesOfItemAtPath:XHRFilePath error:nil][NSFileSize] integerValue];

5. Implementation Of Proxy Method.

Initialized code emulation system, which passes in the block of download progress and the block at completion, to be invoked when appropriate.

/* Download Method. */ - (void)downloadFromURL:(NSString *)urlString progress:(void(^)(CGFloat downloadProgress))downloadProgressBlock complement:(void(^)(NSString *filePath,NSError *error))completeBlock;

When The Server Response Is Received.

// The proxy method called after the server responds. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { // Receive the server response. // Get the full length of the file. taniaarraindegia.esy.esataLengthDictionary[taniaarraindegia.esy.esme] = @([taniaarraindegia.esy.esderFields[@"Content-Length"] integerValue] + XHRAlreadyDownloadLength); [taniaarraindegia.esy.esataLengthDictionary writeToFile:XHRTotalDataLengthDictionaryPath atomically:YES]; // Open outputStream [taniaarraindegia.esy.es open]; // Call the block setting to allow further access. completionHandler(NSURLSessionResponseAllow); }

After Receiving Data, Write It To The Sandbox Bit By Bit.

// A proxy method called after receiving data - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { // Write the data returned from the server into sandbox with stream [taniaarraindegia.esy.es write:taniaarraindegia.esy.es maxLength:taniaarraindegia.esy.es]; taniaarraindegia.esy.esadProgress = * XHRAlreadyDownloadLength / [taniaarraindegia.esy.esataLengthDictionary[taniaarraindegia.esy.esme] integerValue]; }

After Download Is Completed.

// The proxy method invoked after the task is completed. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if (error) { taniaarraindegia.esy.esadError = error; return; } // Close stream. [taniaarraindegia.esy.es close]; // Relaese task. [taniaarraindegia.esy.esn invalidateAndCancel]; taniaarraindegia.esy.essk = nil; taniaarraindegia.esy.esn = nil; // Empty the dictionary that save the file full length. [taniaarraindegia.esy.esataLengthDictionary removeObjectForKey:taniaarraindegia.esy.esme]; [taniaarraindegia.esy.esataLengthDictionary writeToFile:XHRTotalDataLengthDictionaryPath atomically:YES]; !taniaarraindegia.esy.esteBlock?:taniaarraindegia.esy.esteBlock(XHRFilePath,nil); }

Rewrite downloadProgress, downloadError Methods To Listen For Their Values, And Call Back The Corresponding Block Once The Value Is Available.

- (void)setDownloadProgress:(CGFloat)downloadProgress { _downloadProgress = downloadProgress; !taniaarraindegia.esy.esadProgressBlock?:taniaarraindegia.esy.esadProgressBlock(downloadProgress); } - (void)setDownloadError:(NSError *)downloadError { _downloadError = downloadError; !taniaarraindegia.esy.esteBlock?:taniaarraindegia.esy.esteBlock(nil,downloadError); }
Источник: [taniaarraindegia.esy.es]

Nsurlsession download file location

3 thoughts to “Nsurlsession download file location”

Leave a Reply

Your email address will not be published. Required fields are marked *