Asynchronous requests use the same objects as synchronous and queued asynchronous requests, but add another object, Nsurlconnectiondelegate:
On the code:
#import "ViewController.h" Nsintegertotaldownloaded =0; @interface viewcontroller ()@end @implementation viewcontroller - (void) Viewdidload {[SuperViewdidload];additional setup after loading the view, typically from a nib. Nsurl*url = [Nsurlurlwithstring:@"http://www.example.com/test.php"];nsurlrequest*request = [nsurlrequestRequestwithurl:url];nsurlconnection*conn = [nsurlconnectionConnectionwithrequest:request Delegate: Self]; [conn start];}/ * * If the protocol processor receives a redirect request from the server, the method is called */-(nsurlrequest*) Connection: (nsurlconnection*) connection Willsendrequest: (nsurlrequest*) Request Redirectresponse: (Nsurlresponse *) response{//NSLog (@ "All Headers =%@", [(Nshttpurlresponse *) response allheaderfields]); returnRequest;}/* * The Didreceiveresponse method is called when the protocol processor receives enough data to create a URL response object. If an error occurs before you receive enough data to build the object, * The method will not be called * /-(void) Connection: (nsurlconnection*) connection Didreceiveresponse: (Nsurlresponse *) response{nshttpurlresponse *httpresponse = (Nshttpurlresponse *) ResponseNSLog(@"All Headers =%@", [HttpResponse Allheaderfields]);NSLog(@"StatusCode =%ld", (Long) HttpResponse. StatusCode);if(HttpResponse. StatusCode!= $) {[Connection Cancel];return; }}/* * This method is called when the Protocol processor receives some or all of the response body. The method may not be called or may be called multiple times, and the call is always followed by the initial connection:didreceiveresponse * /-(void) Connection: (nsurlconnection*) connection Didreceivedata: (NSData *) data{totaldownloaded + = [data length];NSLog(@"%ld", (Long) totaldownloaded);}/ * * This delegate method is called when the connection fails. The method may be called at any stage of the request processing * /-(void) Connection: (nsurlconnection*) connection Didfailwitherror: (Nserror*) error{NSLog(@"NetWork Connect Error");}/ * * The delegate method is called when the entire request has finished loading and all received data has been passed to the delegate.-(void) Connectiondidfinishloading: (nsurlconnection*) connection{NSLog(@"Finish");} - (void) Didreceivememorywarning {[SuperDidreceivememorywarning];//Dispose of any resources, can be recreated.}@end
IOS---Network asynchronous requests