通过NSURLConnection进行异步下载
NSURLConnection提供了两种方式来实现连接,一种是同步的另一种是异步的,异步的连接将会创建一个新的线程,这个线程将会来负责下载的动作。而对于同步连接,在下载连接和处理通讯时,则会阻塞当前调用线程。
许多开发者都会认为同步的连接将会堵塞主线程,其实这种观点是错误的。一个同步的连接是会阻塞调用它的线程。如果你在主线程中创建一个同步连接,没错,主线程会阻塞。但是如果你并不是从主线程开启的一个同步的连接,它将会类似异步的连接一样。因此这种情况并不会堵塞你的主线程。事实上,同步和异步的主要区别就是运行runtime为会异步连接创建一个线程,而同步连接则不会。
[objc]view plaincopyprint?
//asynchronousRequest connection
-(void)fetchAppleHtml{
NSString*urlString =@"http://www.apple.com";
NSURL*url = [NSURLURLWithString:urlString];
// NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLRequest*urlRequest = [NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheDatatimeoutInterval:30.0f];//maximal timeout is 30s
NSOperationQueue*queue = [[NSOperationQueuealloc]init];
[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError) {
if([datalength] >0&& connectionError ==nil) {
NSString*documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)objectAtIndex:0];
NSString*filePath = [documentsDirstringByAppendingPathComponent:@"apple.html"];
[datawriteToFile:filePathatomically:YES];
NSLog(@"Successfully saved the file to %@",filePath);
NSString*html = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@",html);
}elseif([datalength] ==0&& connectionError ==nil){
NSLog(@"Nothing was downloaded.");
}elseif(connectionError !=nil){
NSLog(@"Error happened = %@",connectionError);
}
}];
}
通过NSURLConnection进行同步下载
使用NSURLConnection的sendSynchronousRequest:returningResponse:error:类方法,我们可以进行同步请求。在创建一个同步的网络连接的时候我们需要明白一点,并不是是我们的这个同步连接一定会堵塞我们的主线程,如果这个同步的连接是创建在主线程上的,那么这种情况下是会堵塞我们的主线程的,其他的情况下是不一定会堵塞我们的主线程的。如果你在GCD的全局并发队列上初始化了一个同步的连接,你其实并不会堵塞我们的主线程的。
我们来初始化第一个同步连接,并看看会发生什么。在实例中,我们将尝试获取Yahoo!美国站点主页内容:
[objc]view plaincopyprint?
//synchronousRequest connection
-(void)fetchYahooData{
NSLog(@"We are here...");
NSString*urlString =@"http://www.yahoo.com";
NSURL*url = [NSURLURLWithString:urlString];
NSURLRequest*urlRequest = [NSURLRequestrequestWithURL:url];
NSURLResponse*response =nil;
NSError*error =nil;
NSLog(@"Firing synchronous url connection...");
NSData*data = [NSURLConnectionsendSynchronousRequest:urlRequestreturningResponse:&responseerror:&error];
if([datalength] >0&& error ==nil) {
NSLog(@"%lu bytes of data was returned.",(unsignedlong)[datalength]);
}elseif([datalength] ==0&& error ==nil){
NSLog(@"No data was return.");
}elseif(error !=nil){
NSLog(@"Error happened = %@",error);
}
NSLog(@"We are done.");
}
/*
|
| as we know, it will chock main thread when we call sendSynchronousRequest on main thread,,,,change below
|
v
*/
//call sendSynchronousRequest on GCD pool
-(void)fetchYahooData2_GCD{
NSLog(@"We are here...");
NSString*urlString =@"http://www.yahoo.com";
NSLog(@"Firing synchronous url connection...");
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(dispatchQueue, ^{
NSURL*url = [NSURLURLWithString:urlString];
NSURLRequest*urlRequest = [NSURLRequestrequestWithURL:url];
NSURLResponse*response =nil;
NSError*error =nil;
NSData*data = [NSURLConnectionsendSynchronousRequest:urlRequestreturningResponse:&responseerror:&error];
if([datalength] >0&& error ==nil) {
NSLog(@"%lu bytes of data was returned.",(unsignedlong)[datalength]);
}elseif([datalength] ==0&& error ==nil){
NSLog(@"No data was returned.");
}elseif(error !=nil){
NSLog(@"Error happened = %@",error);
}
});
NSLog(@"We are done.");
}
查看运行输出结果,分别为:
synchronous download on main thread without GCD
synchronous download on main thread with GCD
可以看到在主线程上调用同步下载会阻塞当前线程,而使用GCD则不会。
通过NSURLConnection发送一个HTTP GET请求
[objc]view plaincopyprint?
//send a GET request to server with some params
-(void)httpGetWithParams{
NSString*urlString =@"http://chaoyuan.sinaapp.com";
urlString = [urlStringstringByAppendingString:@"?p=1059"];
NSURL*url = [NSURLURLWithString:urlString];
NSMutableURLRequest*urlRequest = [NSMutableURLRequestrequestWithURL:url];
[urlRequestsetTimeoutInterval:30.0f];
[urlRequestsetHTTPMethod:@"GET"];
NSOperationQueue*queue = [[NSOperationQueuealloc]init];
[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError) {
if([datalength] >0&& connectionError ==nil) {
NSString*html = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@",html);
}elseif([datalength] ==0&& connectionError ==nil){
NSLog(@"nothing was download.");
}elseif(connectionError !=nil){
NSLog(@"Error happened = %@",connectionError);
}
}];
}
通过NSURLConnection发送一个HTTP POST请求
[objc]view plaincopyprint?
//send a POST request to a server with some params
-(void)httpPostWithParams{
NSString*urlAsString =@"http://chaoyuan.sinaapp.com";
urlAsString = [urlAsStringstringByAppendingString:@"?param1=First"];
urlAsString = [urlAsStringstringByAppendingString:@"¶m2=Second"];
NSURL*url = [NSURLURLWithString:urlAsString];
NSMutableURLRequest*urlRequest = [NSMutableURLRequestrequestWithURL:url]; [urlRequestsetTimeoutInterval:30.0f];
[urlRequestsetHTTPMethod:@"POST"];
NSString*body =@"bodyParam1=BodyValue1&bodyParam2=BodyValue2"; [urlRequestsetHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];NSOperationQueue*queue = [[NSOperationQueuealloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,
NSError*error) {
if([datalength] >0&&
error ==nil){
NSString*html = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html);
}
elseif([datalength] ==0&&
error ==nil){
NSLog(@"Nothing was downloaded.");
}
elseif(error !=nil){
NSLog(@"Error happened = %@", error);
}
}];
}