NSURLSession経由でHTTP requestを投げるサンプルコード Swift版


# GET HTTP Request (非同期)
```swift
import UIKit

//playgroundで実行する際に必要なだけ
import XCPlayground

//Construct url object via string
var url = NSURL(string: "http://www.example.com/")
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
var req = NSURLRequest(URL: url!)

//NSURLSessionDownloadTask is retured from session.dataTaskWithRequest
var task = session.dataTaskWithRequest(req, completionHandler: {
    (data, resp, err) in
        println(resp.URL!)
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    })
task.resume()

//playgroundで実行する際に必要なだけ
XCPSetExecutionShouldContinueIndefinitely()

```

[URL Loading System Programming Guide](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html)
[NSURLSession のまとめ](http://qiita.com/aKentaKoyama/items/96a979ab3a140e7b39ec)


# POST HTTP Request

下記のようにncコマンドでlistenしておくと、postされるリクエストをターミナルで見る事ができるので、オススメ。

```bash
$nc -l 1234
```

- Getのコードとの差はHTTPMethodとHTTPBodyのプロパティの値だけ

```swift
import UIKit

//playgroundで実行する際に必要なだけ
import XCPlayground

//Construct url object via string
var url = NSURL(string: "http://localhost:1234/")
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
var req = NSMutableURLRequest(URL: url!)
req.HTTPMethod = "POST"
req.HTTPBody = "id=13&name=Jack".dataUsingEncoding(NSUTF8StringEncoding)
var task = session.dataTaskWithRequest(req, completionHandler: {
    (data, resp, err) in
        println(resp.URL!)
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    })
task.resume()

//playgroundで実行する際に必要なだけ
XCPSetExecutionShouldContinueIndefinitely()

```

# JSON POST HTTP Request

- 通常のPOSTとの差はContentTypeの指定とBody部分のデータをNSJSONSerialization経由でJSON化する部分くらい

```swift
import UIKit

//playgroundで実行する際に必要なだけ
import XCPlayground

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)

//Construct url object via string
var url = NSURL(string: "http://localhost:1234/")
//Construct object to be converted to json
let params:[String: AnyObject] = [
    "email" : "aaaa",
    "userPwd" : "bbbb" ]
var req = NSMutableURLRequest(URL: url!)
req.HTTPMethod = "POST"
req.setValue("application/json; charaset=utf-8", forHTTPHeaderField: "Content-Type")

//Convert founcation object to json and set to HTTP body
var err: NSError?
req.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)

var task = session.dataTaskWithRequest(req, completionHandler: {
    (data, resp, err) in
        println(resp.URL!)
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    })
task.resume()

//playgroundで実行する際に必要なだけ
XCPSetExecutionShouldContinueIndefinitely()

```

###NSJSONSerialization
- JSONとFoundationオブジェクトの変換を行うクラス

[NSJSONSerialization Class Reference](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/index.html)

[How to POST JSON data using NSURLSession in swift](http://stackoverflow.com/questions/27036233/how-to-post-json-data-using-nsurlsession-in-swift)