The process of downloading a file using Nsurlsessiondownloadtask is similar to the previous one, it is important to note that the file download file is automatically saved to a temporary directory, requiring the developer to re-place the file in another specified directory.
////VIEWCONTROLLER.M//nsurlsession////copyright©2016 year Asamu. All rights reserved.//#import "ViewController.h"@interfaceViewcontroller ()@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; [Self downLoadFile];}-(void) downloadfile{//1. Create a URLNSString *filename =@"1.jpg"; NSString*URLSTR = [NSString stringWithFormat:@"http://img3.douban.com/lpic/s4717862.jpg", FileName]; Urlstr=[Urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; Nsurl*url =[Nsurl Urlwithstring:urlstr]; //2. Create a requestNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //Create a sessionNsurlsession *session =[Nsurlsession sharedsession]; Nsurlsessiondownloadtask*downloadtask = [Session downloadtaskwithrequest:request completionhandler:^ (Nsurl * _nullable location, NSURLResponse * _nullable response, Nserror *_nullable Error) { if(!error) { //location is the temporary save path after download, it needs to be moved to the place where it needs to be savedNserror *saveerror =Nil; NSString*cachepath =[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; NSString*savepath =[CachePath Stringbyappendingstring:filename]; NSLog (@"%@", Savepath); Nsurl*url =[Nsurl Fileurlwithpath:savepath]; [[Nsfilemanager defaultmanager]copyitematurl:location tourl:url Error:&Saveerror]; if(!saveerror) {NSLog (@"Save Success"); }Else{NSLog (@"error is:%@", saveerror.localizeddescription); } }Else{NSLog (@"error is:%@", error.localizeddescription); } }]; //Perform Tasks[Downloadtask resume];}- (void) didreceivememorywarning {[Super didreceivememorywarning];}@end
From Kenshincui, link to the previous article.
iOS Learning-10 downloads (2) nsurlsession