iOS core note-Network programming-nsurlsessiondownloadtask

Source: Internet
Author: User

1, large file download: 1-1, create download task: Mode one: At the same time set up the agent to listen to the download progress:
1.-(void)downloadDelegate
2.{
3. //01 确定资源路径
4. NSURL *url = [NSURL URLWithString:@"http://img4q.duitang.com/uploads/item/201406/09/20140609150919_ZztLd.jpeg"];
5.
6. //02 创建请求对象
7. NSURLRequest *request = [NSURLRequest requestWithURL:url];
8.
9. //03 创建会话对象 设置代理
10. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
11.
12. //04 创建downloadTask
13. NSURLSessionDownloadTask *downloadTask =[session downloadTaskWithRequest:request];
14.
15. //05 发送请求
16. [downloadTask resume];
17.
18.}
Mode two: Create the Nsurlsessiondownloadtask object directly:
1.//disadvantage: Unable to listen to the progress of the file
2.-(void) Download
3.{
4.//01 Determine the resource path
5. Nsurl *url = [Nsurl urlwithstring:@ "Http://img4q.duitang.com/uploads/item/201406/09/20140609150919_ZztLd.jpeg"];
6.
7.//02 Create Request Object
8. Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
9.
10.//03 Creating a Session Object
Nsurlsession *session = [Nsurlsession sharedsession];
12.
13.//04 Create Downloadtask
14./* Parameter description
15. *
16. * First parameter: Request object
17. * Second parameter: Completionhandler when a request is completed (Success | failed)
* location: The position of the file has been implemented within the edge of the data side write sandbox operation
* Response: Response header information
20. */
Nsurlsessiondownloadtask *downloadtask = [Session downloadtaskwithrequest:request completionhandler:^ (NSURL * _Nul lable location, Nsurlresponse * _nullable response, Nserror * _nullable error) {
22.//The data is written to disk by default: tmp/... may be removed at any time
23.
24.//Transfer files (transfer to a safe place)
NSString *cachepath = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject ];
NSString *fullpath = [CachePath stringByAppendingPathComponent:response.suggestedFilename];
27.
28.//Path->nsurl
//urlwithstring does not do any additional processing.
//fileurlwithpath.
NSLog (@ "%@", [Nsurl Urlwithstring:fullpath]);
NSLog (@ "%@", [Nsurl Fileurlwithpath:fullpath]);
33.
[[Nsfilemanager Defaultmanager] moveitematurl:location tourl:[nsurl Fileurlwithpath:fullpath] error:nil];
35.}];
36.
37.//05 Send Request
[Downloadtask resume];
39.}
1-2, Nsurlsessiondownloadtask common agent method:
1.#pragma mark NSURLSessionDownloadDelegate
2.
3.//01 写数据的时候调用
4.// bytesWritten 本次写入的数据大小
5.// totalBytesWritten 写入数据的总大小
6.// totalBytesExpectedToWrite 文件的总大小
7.-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
8.{
9. NSLog(@"%f",1.0 * totalBytesWritten / totalBytesExpectedToWrite);
10.}

?重要: Called when starting to write data to a file in the default path in the app sandbox.

1.//02 下载完成的时候调用
2.-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
3.{
4. //转移文件(转移到安全的地方去)
5. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
6. NSString *fullPath = [cachePath stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
7.
8. //剪切文件
9. [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
10.}

?重要: This method is called when the download is complete and the file under the path is deleted when the default download completes, so you need to transfer the file to a different secure path when the download is complete.

1.//03 整个请求结束或者是失败的时候调用
2.-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
3.{
4. NSLog(@"didCompleteWithError");
5.}

?重要: Called when the download task finishes or fails.

2, the breakpoint continued to pass:

?重要: 1, NSURLSessionDownloadTask can use suspend(挂起下载任务) ,,, resume(启动下载任务) cancel(不可恢复取消下载任务) cancelByProducingResumeData:(可恢复下载任务) operation download Task.

?重要: 2, NSURLSessionDownloadTask the use of cancel the method to cancel the download operation will not be able to resume the download task (that is, the use of the cancel method is canceled after the breakpoint can not be resumed, because, downloadtask if not special processing, the download operation completed or use cancel Method Cancel will immediately delete the file saved in the sandbox path, so you cannot use NSURLSessionDownloadTask the offline download function or use the cancel method to implement the breakpoint continuation function.

?重要: 3, use cancelByProducingResumeData: the method to cancel the download task, the use of attributes resumeData to save data, you can implement the breakpoint continuation function.

?重要: 4, Resumedata: Can be used to restore the downloaded data, not the sandbox saved in the downloaded file data.

2-1. Use the properties to save the restore download operation requiredresumeDataData:
[email protected] (nonatomic, strong) NSData *resumeData;
2-2. UsecancelByProducingResumeData:To pause the download operation:
1.- (IBAction)cacnelBtnClick:(id)sender
2.{
3. //取消 普通的取消操作是不可以恢复的
4. //[self.downloadTask cancel];
5.
6. //取消,可以恢复的取消操作
7. //resumeData 可以用来恢复下载的数据 并不是沙盒中保存的已经下载好的文件数据
8. [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
9. self.resumeData = resumeData;
10. }];
11.
12. self.downloadTask = nil;
13. NSLog(@"取消下载任务+++");
14.}
2-3. Resume Download Task:
1.- (IBAction)resumeBtnClick:(id)sender
2.{
3. //暂停->恢复
4. if(self.resumeData)
5. {
6. //取消->恢复
7. //在恢复下载的时候,判断是否有可以用来进行恢复下载的数据,如果有那么就根据该数据创建一个新的网络请求
8. self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
9. self.resumeData = nil;
10. }
11.
12. [self.downloadTask resume];
13.}

iOS core note-Network programming-nsurlsessiondownloadtask

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.