Playground でURLSessionを試す(GET編)

iOSの標準ライブラリーだけで通信処理をすることになったのでこの基にURLSessionの使い方をみてみる

環境

  • Xcode8 bata4
  • Swift3
  • Playground

サーバーはWebAPIをとりあえず試せるサイトhttp://httpbin.org/を使用します

GETで実行

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

//Construct url object via string
var url = NSURL(string: "http://httpbin.org/get")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
var req = URLRequest(url: url! as URL)

//NSURLSessionDownloadTask is retured from session.dataTaskWithRequest
let task = session.dataTask(with: req as URLRequest, completionHandler: {
    (data, resp, err) in
    print(resp?.url!)
    print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue))
})
task.resume()

//非同期処理を許可する
PlaygroundPage.current.needsIndefiniteExecution = true

結果

Optional(http://httpbin.org/get)
Optional({
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Accept-Language": "en-us", 
    "Host": "httpbin.org", 
    "User-Agent": "NSSessionSample/1 CFNetwork/802.1 Darwin/15.6.0"
  }, 
  "origin": "126.126.186.75", 
  "url": "http://httpbin.org/get"
}
)