NSURLSession for IOS Network Development (iii) DownloadTask and nsurlsession

Source: Internet
Author: User

NSURLSession for IOS Network Development (iii) DownloadTask and nsurlsession

Original Blog, reprinted, please indicate the source
Blog.csdn.net/hello_hwc

Demo Effect
Download a URL, display the ImageView, and save it to the album.

Previous album

Album after saving the image

Differences between DownloadTask and DataTask

In short, DownloadTask downloads files directly to the disk.
In details, there are the following differences:

Second, use the Block method to process DownloadTask

In this case, it is similar to DataTask, which is easy to process but not flexible.
The Location is the path of the download temporary file storage.

 self.downloadTask = [self.session downloadTaskWithURL:(NSURL *) completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {    }];

Continue the last saved data download

    self.downloadTask = [self.session downloadTaskWithResumeData:(NSData *) completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {    }]

The ResumeData here is through

[self.downloadTask cancelByProducingResumeData:^(NSData *resumeData)completionHandler]

Or store it in the Error of the Session proxy function. The Key is NSURLSessionDownloadTaskResumeData.

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
3. Proxy-based processing

In addition to NSURLSessionDelegate, NSURLSessionTaskDelegate processes common events of tasks, and NSURLSessionDownloadTaskDelegate processes Download events in particular.
Several main functions

After DownloadTask is created with ResumeData in the preceding section, the function is called every time the task is executed.

- (void)URLSession:(NSURLSession *)session      downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffsetexpectedTotalBytes:(int64_t)expectedTotalBytes

Download progress

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

Download completed event
Note that you must use or save the data before the function returns.

- (void)URLSession:(NSURLSession *)session      downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location
4. Demo

Demo is relatively simple,

@ Interface DownloadTaskViewController () <NSURLSessionDelegate, response, response> @ property (strong, nonatomic) NSURLSession * session; @ property (strong, nonatomic) NSURLSessionDownloadTask * downloadTask; @ property (weak, nonatomic) IBOutlet UITextField * urltextfield; @ property (weak, nonatomic) IBOutlet UIImageView * imageview; @ property (weak, nonatom Ic) IBOutlet UIProgressView * progressview; @ end @ implementation DownloadTaskViewController // start download-(IBAction) download :( id) sender {self. progressview. hidden = NO; self. progressview. progress = 0.0; NSString * imageurl = self. urltextfield. text; self. downloadTask = [self. session downloadTaskWithURL: [NSURL URLWithString: imageurl]; [self. downloadTask resume]; [self. session finishTasksAndInvalidate];} // Initialization -(Void) viewDidLoad {self. urltextfield. delegate = self; NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @ "id"]; self. session = [NSURLSession sessionWithConfiguration: configuration delegate: self delegateQueue: [NSOperationQueue mainQueue];} // event of Task completion at the Session level-(void) URLSession :( NSURLSession *) session task :( NSURLSessionTask *) task d IdCompleteWithError :( NSError *) error {if (error) {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "Error" message: error. localizedDescription delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil]; [alert show];} self. progressview. hidden = YES;} // The Event completed by the Task-(void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) downloadTask didFinishDownloadingToURL :( NSUR L *) location {NSData * data = [NSData dataWithContentsOfURL: location. filePathURL]; UIImage * image = [UIImage imageWithData: data]; self. imageview. image = image; UIImageWriteToSavedPhotosAlbum (image, nil); self. session = nil;}-(void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) downloadTask didResumeAtOffset :( int64_t) fileOffset expectedTotalBytes :( int64_t) limit C TedTotalBytes {} // The download progress proxy-(void) URLSession :( NSURLSession *) session downloadTask :( bytes *) downloadTask didWriteData :( int64_t) bytesWritten minutes :( int64_t) interval :( int64_t) totalBytesExpectedToWrite {if (totalBytesExpectedToWrite! = NSURLSessionTransferSizeUnknown) {self. progressview. progress = totalBytesWritten/(float) totalBytesExpectedToWrite; }}// TextField Delegate-(BOOL) textFieldShouldReturn :( UITextField *) textField {[self. urltextfield resignFirstResponder]; return YES ;}@ end

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.