ios – NSURLSession的HTTP数据任务(NSURLSessionDataTask)是否在后台线程中运行,否则我们将不得不提供队列?

前端之家收集整理的这篇文章主要介绍了ios – NSURLSession的HTTP数据任务(NSURLSessionDataTask)是否在后台线程中运行,否则我们将不得不提供队列?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我开始使用NSURLSession,因为它是由Apple提供的一个新的优雅API,现在避免使用NSURLConnection.以前,我曾经在GCD块中调用NSURLRequest来在后台执行它.以下是我过去曾经做过的事情:
  1. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
  2.  
  3. NSURLRequest *request = [NSURLRequest requestWithURL:
  4. [NSURL URLWithString:@"www.stackoverflow.com"]];
  5. NSURLResponse *response;
  6. NSError *error;
  7. NSData *data = [NSURLConnection sendSynchronousRequest:request
  8. returningResponse:&response
  9. error:&error];
  10. if (error) {
  11. // handle error
  12. return;
  13. }
  14. dispatch_async(dispatch_get_main_queue(),^{
  15. // do something with the data
  16. });
  17. });

现在,这是我如何使用NSURLSession:

  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4.  
  5. /*-----------------*
  6. NSURLSession
  7. *-----------------*/
  8.  
  9. NSURLSession *session = [NSURLSession sharedSession];
  10.  
  11. NSURLSessionDataTask *dataTask = [session dataTaskWithURL:
  12. [NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"]
  13. completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
  14. {
  15. NSDictionary *json = [NSJSONSerialization
  16. JSONObjectWithData:data options:0 error:nil];
  17. NSLog(@"%@",json);
  18. }];
  19. }

我想知道,我的请求是否会在后台线程本身执行,否则我将必须提供与NSURLRequest相同的方式.

分享你的知识.提前致谢 !!!

解决方法

不,您不需要使用GCD将它分派到后台队列.实际上,因为完成块在后台线程上运行,所以恰恰相反,如果你需要任何东西在该块中在主队列上运行(例如,对模型对象的同步更新,UI更新等),你有手动将其分派到主队列.例如,我们假设您要检索一个结果列表并更新UI以反映这一点,您可能会看到如下:
  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4.  
  5. NSURLSession *session = [NSURLSession sharedSession];
  6.  
  7. NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data,NSError *error) {
  8. // this runs on background thread
  9.  
  10. NSError *error;
  11. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  12.  
  13. // detect and handle errors here
  14.  
  15. // otherwise proceed with updating model and UI
  16.  
  17. dispatch_async(dispatch_get_main_queue(),^{
  18. self.searchResults = json[@"results"]; // update model objects on main thread
  19. [self.tableView reloadData]; // also update UI on main thread
  20. });
  21.  
  22. NSLog(@"%@",json);
  23. }];
  24.  
  25. [dataTask resume];
  26. }

猜你在找的iOS相关文章