博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NSURLConnection
阅读量:6150 次
发布时间:2019-06-21

本文共 6807 字,大约阅读时间需要 22 分钟。

通过NSURLConnection进行异步下载   

      NSURLConnection 提供了两种方式来实现连接,一种是同步的另一种是异步的,异步的连接将会创建一个新的线程,这个线程将会来负责下载的动作。而对于同步连接,在下载连接和处理通讯时,则会阻塞当前调用线程。

     许多开发者都会认为同步的连接将会堵塞主线程,其实这种观点是错误的。一个同步的连接是会阻塞调用它的线程。如果你在主线程中创建一个同步连接,没错,主线程会阻塞。但是如果你并不是从主线程开启的一个同步的连接,它将会类似异步的连接一样。因此这种情况并不会堵塞你的主线程。事实上,同步和异步的主要区别就是运行 runtime 为会异步连接创建一个线程,而同步连接则不会

objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片//asynchronousRequest connection  -(void)fetchAppleHtml{      NSString *urlString = @"http://www.apple.com";      NSURL *url = [NSURL URLWithString:urlString];  //    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];      NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0f]; //maximal timeout is 30s            NSOperationQueue *queue = [[NSOperationQueue alloc] init];      [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {          if ([data length] > 0 && connectionError == nil) {              NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];              NSString *filePath = [documentsDir stringByAppendingPathComponent:@"apple.html"];              [data writeToFile:filePath atomically:YES];              NSLog(@"Successfully saved the file to %@",filePath);              NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];              NSLog(@"HTML = %@",html);          }else if ([data length] == 0 && connectionError == nil){              NSLog(@"Nothing was downloaded.");          }else if (connectionError != nil){              NSLog(@"Error happened = %@",connectionError);          }      }];  }

  

通过NSURLConnection进行同步下载   

 

   使用 NSURLConnection 的 sendSynchronousRequest:returningResponse:error:类方法,我们可以进行同步请求。在创建一个同步的网络连接的时候我们需要明白一点,并不是是我们的这个同步连接一定会堵塞我们的主线程,如果这个同步的连接是创建在主线程上的,那么这种情况下是会堵塞我们的主线程的,其他的情况下是不一定会堵塞我们的主线程的。如果你在 GCD 的全局并发队列上初始化了一个同步的连接,你其实并不会堵塞我们的主线程的。

   我们来初始化第一个同步连接,并看看会发生什么。在实例中,我们将尝试获取 Yahoo!美国站点主页内容: 

 

//synchronousRequest connection  -(void)fetchYahooData{      NSLog(@"We are here...");      NSString *urlString = @"http://www.yahoo.com";      NSURL *url = [NSURL URLWithString:urlString];      NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];      NSURLResponse *response = nil;      NSError *error = nil;      NSLog(@"Firing synchronous url connection...");      NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];      if ([data length] > 0 && error == nil) {          NSLog(@"%lu bytes of data was returned.",(unsigned long)[data length]);      }else if([data length] == 0 && error == nil){          NSLog(@"No data was return.");      }else if (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 = [NSURL URLWithString:urlString];          NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];          NSURLResponse *response = nil;          NSError *error = nil;          NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];          if ([data length] > 0 && error == nil) {              NSLog(@"%lu bytes of data was returned.",(unsigned long)[data length]);          }else if ([data length] == 0 && error == nil){              NSLog(@"No data was returned.");          }else if (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请求

 

//send a GET request to server with some params  -(void)httpGetWithParams{      NSString *urlString = @"http://chaoyuan.sinaapp.com";      urlString = [urlString stringByAppendingString:@"?p=1059"];      NSURL *url = [NSURL URLWithString:urlString];      NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];      [urlRequest setTimeoutInterval:30.0f];      [urlRequest setHTTPMethod:@"GET"];      NSOperationQueue *queue = [[NSOperationQueue alloc] init];      [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {          if ([data length] > 0 && connectionError == nil) {              NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];              NSLog(@"HTML = %@",html);          }else if([data length] == 0 && connectionError == nil){              NSLog(@"nothing was download.");          }else if(connectionError != nil){              NSLog(@"Error happened = %@",connectionError);          }      }];  }    通过NSURLConnection发送一个HTTP POST请求[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片//send a POST request to a server with some params  -(void)httpPostWithParams{      NSString *urlAsString = @"http://chaoyuan.sinaapp.com";      urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];      urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];      NSURL *url = [NSURL URLWithString:urlAsString];      NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f];      [urlRequest setHTTPMethod:@"POST"];      NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2"; [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc] init];      [NSURLConnection       sendAsynchronousRequest:urlRequest       queue:queue completionHandler:^(NSURLResponse *response, NSData *data,                                       NSError *error) {           if ([data length] >0 &&               error == nil){               NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html);           }           else if ([data length] == 0 &&                    error == nil){               NSLog(@"Nothing was downloaded.");           }           else if (error != nil){               NSLog(@"Error happened = %@", error);           }       }];  }

  

转载于:https://www.cnblogs.com/deng37s/p/4600577.html

你可能感兴趣的文章
使用FMDB最新v2.3版本教程
查看>>
SSIS从理论到实战,再到应用(3)----SSIS包的变量,约束,常用容器
查看>>
STM32启动过程--启动文件--分析
查看>>
垂死挣扎还是涅槃重生 -- Delphi XE5 公布会归来感想
查看>>
淘宝的几个架构图
查看>>
Android扩展 - 拍照篇(Camera)
查看>>
数据加密插件
查看>>
linux后台运行程序
查看>>
win7 vs2012/2013 编译boost 1.55
查看>>
IIS7如何显示详细错误信息
查看>>
Tar打包、压缩与解压缩到指定目录的方法
查看>>
配置spring上下文
查看>>
Python异步IO --- 轻松管理10k+并发连接
查看>>
Oracle中drop user和drop user cascade的区别
查看>>
登记申请汇总
查看>>
Office WORD如何取消开始工作右侧栏
查看>>
Android Jni调用浅述
查看>>
CodeCombat森林关卡Python代码
查看>>
第一个应用程序HelloWorld
查看>>
(二)Spring Boot 起步入门(翻译自Spring Boot官方教程文档)1.5.9.RELEASE
查看>>