これは Apple が提供する新しいエレガントな API なので、最近はNSURLSession
避けて使用し始めました。以前は、バックグラウンドで実行するために呼び出しをブロックに入れていました。以前は次のようにしていました。NSURLConnection
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
。
ベストアンサー1
いいえ、これをバックグラウンド キューにディスパッチするために 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];
}