我开始使用NSURLSession
,现在避免使用NSURLConnection
,因为这是苹果提供的新的优秀API。 以前,我曾经将调用NSURLRequest
放入GCD
块中以在后台执行它。以下是我过去的做法:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:@"www.stackoverflow.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
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
*-----------------*/
NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(@"%@", json);
}];
}
我想知道,我的请求会在后台线程上执行,还是我需要提供自己的机制,就像我在使用NSURLRequest
时一样?
sendAsynchronousRequest
仍在后台运行... - NSPratikNSURLSession
方法。地理编码器和位置搜索方法。许多Cocoa方法在后台线程异步执行并带有完成块/闭包。 - Rob