Nsurlsession *session = [Nsurlsession sharedsession];
Can not be like connection with agent monitoring, directly download files, but is unable to obtain the progress of the download
nsurlsessiondownloadtask *task = [session
Downloadtaskwithurl:[nsurl urlwithstring:@ ""]
completionhandler:^ (Nsurl * _nullable location, Nsurlresponse * _nullable response, Nserror * _nullable error) {
//real path to file storage
NSString *file = [[Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject ] StringByAppendingPathComponent:response.suggestedFilename];
//Cut temporary files for location to the real path
Nsfilemanager *mgr = [Nsfilemanager Defaultmanager];
[Mgr moveitematurl: Location tourl:[Nsurl Fileurlwithpath:file] error:nil];
}];
[Task resume];
///////////////////////////////////////////////////////////////////////////////////////////////////////////
Three protocols, but the most basic of which is the inheritance of the Protocol
@interface Viewcontroller () <nsurlsessionDatadelegate>//inheriting subclasses is equivalent to inheriting the parent class protocol
@end
Inheritance relationship between protocols: <nsurlsessionDatadelegate>:<nsurlsessionTaskdelegate>:< Nsurlsessiondelegate>
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
Nsurlsession *session = [Nsurlsession sharedsession];
Session.delegate = self; Cannot directly set delegate is ReadOnly
Can only be created at the beginning of its agent
Nsurlsession *session = [nsurlsession sessionwithconfiguration: [nsurlsessionconfiguration Defaultsessionconfiguration] Delegate: self delegatequeue:[[nsoperationqueue alloc] init]];
Parent protocol, but can pass in sub-protocol: Nullable ID <NSURLSessionDelegate>
Nsurlsessiondownloadtask *task = [Session downloadtaskwithrequest:[nsurlrequest Requestwithurl:[nsurl URLWithString: @ ""]] completionhandler:^ (nsurl * _nullable location, Nsurlresponse * _nullable response, Nserror * _nullable error) {}];
[Task resume];
}
Proxy method
-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceiveresponse:( Nsurlresponse *) Response Completionhandler: (void (^) (nsurlsessionresponsedisposition)) completionhandler{
To start, otherwise it cannot be downloaded
Completionhandler (Nsurlsessionresponseallow);//Allow to continue request number after
}
-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceivedata:( NSData *) data{
}
-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) error{
}
IOS uses nsurlsession to download large files