NSURLSessionTask也可以用来发送网络请求, 相对NSURLConnection, 推荐使用NSURLSessionTask.
a.NSURLSessionTask是一个抽象类,本身不能使用,只能使用它的子类
B.nsurlsessiondatatask\nsurlsessionuploadtask\nsurlsessiondownloadtaskBasic Use (get/post) with
NSURLConnection
similar:
-(void)Get1{ //1. Create a request pathNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON"]; //2. Create a Request objectNsurlrequest *request =[Nsurlrequest Requestwithurl:url]; //3. Creating a Session ObjectNsurlsession *session =[Nsurlsession sharedsession]; //4. Create a task /*first parameter: Request object second parameter: Completionhandlerblock data: Response Body Response: Response header error: Wrong message*/Nsurlsessiondatatask*datatask = [Session datataskwithrequest:request completionhandler:^ (NSData * _nullable data, Nsurlresponse * _Nullable R Esponse, Nserror *_nullable Error) { //6. Parsing DataNSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]); }]; //5. Start the execution[Datatask resume];}-(void) get2{//1. Create a request pathNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON"]; //3. Creating a Session ObjectNsurlsession *session =[Nsurlsession sharedsession]; //4. Create a task /*first parameter: Request object second parameter: Completionhandlerblock data: Response Body Response: Response header error: Wrong message*/Nsurlsessiondatatask*datatask = [Session Datataskwithurl:url completionhandler:^ (NSData * _nullable data, Nsurlresponse * _Nullable response, Nserror *_nullable Error) { //6. Parsing DataNSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]); }]; //5. Start the execution[Datatask resume];}-(void) post{//1. Create a request pathNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/login"]; //2. Create a Request objectNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; Request. HttpMethod=@"POST"; Request. Httpbody= [@"Username=520it&pwd=123&type=json"datausingencoding:nsutf8stringencoding]; //3. Creating a Session ObjectNsurlsession *session =[Nsurlsession sharedsession]; //4. Create a task /*first parameter: Request object second parameter: Completionhandlerblock data: Response Body Response: Response header error: Wrong message*/Nsurlsessiondatatask*datatask = [Session datataskwithrequest:request completionhandler:^ (NSData * _nullable data, Nsurlresponse * _Nullable R Esponse, Nserror *_nullable Error) { //6. Parsing DataNSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]); }]; //5. Start the execution[Datatask resume];}
iOS Network-nsurlsessiontask Simple Introduction