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

我开始使用NSURLSession,因为它是由Apple提供的一个新的优雅API,现在避免使用NSURLConnection.以前,我曾经在GCD块中调用NSURLRequest来在后台执行它.以下是我过去曾经做过的事情:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{

    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"www.stackoverflow.com"]];
    NSURLResponse *response;
    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:request 
                                         returningResponse:&response 
                                                     error:&error];
    if (error) {
        // handle error
        return;
    }
    dispatch_async(dispatch_get_main_queue(),^{
        // do something with the data
    });
});

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

- (void)viewDidLoad 
{
    [super viewDidLoad];

    /*-----------------*
        NSURLSession
     *-----------------*/

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:
                                  [NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] 
                                     completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) 
{
    NSDictionary *json = [NSJSONSerialization 
                          JSONObjectWithData:data options:0 error:nil];
    NSLog(@"%@",json);
}];
}

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

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

解决方法

不,您不需要使用GCD将它分派到后台队列.实际上,因为完成块在后台线程上运行,所以恰恰相反,如果你需要任何东西在该块中在主队列上运行(例如,对模型对象的同步更新,UI更新等),你有手动将其分派到主队列.例如,我们假设您要检索一个结果列表并更新UI以反映这一点,您可能会看到如下:
- (void)viewDidLoad 
{
    [super viewDidLoad];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data,NSError *error) {
        // this runs on background thread

        NSError *error;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

        // detect and handle errors here

        // otherwise proceed with updating model and UI

        dispatch_async(dispatch_get_main_queue(),^{
            self.searchResults = json[@"results"];    // update model objects on main thread
            [self.tableView reloadData];              // also update UI on main thread
        });

        NSLog(@"%@",json);
    }];

    [dataTask resume];
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...