LoginSignup
35
34

More than 5 years have passed since last update.

SwiftでNSURLSession

Posted at

NSURLSessionでWebページから情報を取ってくるのをSwiftで。
Objective-Cの時と比べて、completionHandlerがスッキリしてる。

import Foundation

let url  = NSURL.URLWithString("http://qiita.com/")
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task    = session.dataTaskWithURL(url, completionHandler: {
    (data, resp, err) in
        println(NSString(data: data, encoding:NSUTF8StringEncoding))
    })

task.resume()

Objective-Cだとこうでした

NSURL            *url     = [NSURL URLWithString:@"http://qiita.com/"];
NSURLSession     *session = [NSURLSession defaultSessionConfiguration];
NSURLSessionTask *task = [session dataTaskWithURL:url
  completionHandler:^(NSData *data, NSURLResponse *resp, NEError *err) {
    NSString *res = [[NSString alloc]initWithData:data encoding: NSUTF8StringEncoding];
    NSLog(@"%@", res);
}];

[task resume];
35
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
34