Asynchronous download: supports downloading data from the application in the background. code execution is not blocked while the download is complete.
Synchronous download: when calling a method, if the return of the method depends on whether its function is complete, the method is called a synchronous method. The download is complete before proceeding to the next step. The system will be shelled.
Synchronous download:
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
Form 1:
NSString *str=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
Form 2:
NSData * _data =[NSData dataWithContentsOfURL:url]
Form 3:
NSURLRequest *request=[NSURLRequest requestWithURL:url1]; NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
Asynchronous download:
Form 1:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"------%d",data.length); [data writeToFile:path atomically:YES];
Form 2:
First, the Protocol <nsurlconnectiondatadelegate>
Define global variables:
Nsmutabledata * _ totaldata;
Long long _ totallength;
// Download preparation
1 NSURL *url=[NSURL URLWithString:@"http://class.room/hdmv.mp4"];2 NSURLRequest *request=[NSURLRequest requestWithURL:url];3 NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];4 [connection start];
// Methods in the Implementation Protocol
// 1. first, obtain the response information to know what the received data is like-(void) connection :( nsurlconnection *) connection didreceiveresponse :( nsurlresponse *) response {// data size _ totallength = response. expectedcontentlength;} // nsfilehandle // 2. accept data in multiple stages-(void) connection :( nsurlconnection *) connection didreceivedata :( nsdata *) Data {[_ totaldata appenddata: Data];} // 3. download complete-(void) connectiondidfinishloading :( nsurlconnection *) connection {nslog (@ "finished... ");}
But it is used for multiple data and multiple Content downloads, which leads to confusion. Therefore, you can encapsulate this download method to download a few objects. There will be no confusion.