NSP*_*tik 12 multithreading ios nsurlsession nsurlsessiontask nsurlsessiondatatask
我现在开始使用NSURLSession,NSURLConnection因为它是Apple提供的一种新的优雅API.以前,我曾经NSURLRequest在GCD块中调用来在后台执行它.以下是我过去的做法:
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
});
});
Run Code Online (Sandbox Code Playgroud)
现在,我的使用方法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);
}];
}
Run Code Online (Sandbox Code Playgroud)
我想知道,我的请求是否会在后台线程本身执行,或者我必须以同样的方式提供我自己的机制NSURLRequest?
Rob*_*Rob 39
不,您不需要使用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, NSURLResponse *response, 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];
}
Run Code Online (Sandbox Code Playgroud)