3

我正在使用 iOS 7 NSURLSession 对 RESTful 服务进行一些简单的 GET 操作。这就是我所做的:

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration ephemeralSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:[NSOperationQueue mainQueue]]; 

// create your url at this line
NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLSessionTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
   // do something with the result 
}]; 
[task resume];

以上所有代码都可以正常工作。completionHandler 应该在主队列中被调用。

但是,如果我在 GCD 中使用它,就像这样:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   // do some heavylifting in the background

   for (int i = 0; i < 10000000; i++) ;

   dispatch_async(dispatch_get_main_queue(), ^{
       // do the exact same thing as the above NSURLSession call
       NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration ephemeralSessionConfiguration];
       _session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:[NSOperationQueue mainQueue]]; 

       // create your url at this line
       NSURLRequest *request = [NSURLRequest requestWithURL:url];

       NSURLSessionTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
          // do something with the result 
       }]; 
       [task resume];
   });
});

现在,我想我在 dispatch_get_main_queue() 中运行该代码,它应该与会话的 delegateQueue 中指定的 [NSOperationQueue mainQueue] 相同?Tt 应该像第一组代码一样有效地在主线程中运行。但是,我发现完成处理程序永远不会被调用。如果我删除 GCD 代码,它会再次工作。

有没有人尝试过这样做?这应该工作吗?或者我误解了工作被分派到了哪个队列?

4

1 回答 1

0

AFAIK,所有NSURLSession回调都发生在只读NSURLSession. delegateQueue属性(docs)指定的队列上,该属性可以在初始化时指定。

于 2014-02-10T20:18:45.310 回答