非同期で指定URLにアクセスする - iOS開発メモ

サンプル

NSURLSessionTaskを使います。

NSURL *url = [NSURL URLWithString:@"http://www.example.com"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error == nil) {
        NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;
        if (statusCode == 200) {
            NSString *downloadData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"data = %@", downloadData);
        } else {
            NSLog(@"http error. code = %ld", (long)statusCode);
        }
    } else {
        NSLog(@"error = %@", [error localizedDescription]);
    }

    [session invalidateAndCancel];
}
                          ];

[task resume];

関連項目