75
78

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

GET HTTP Request (非同期)

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
NSURLSession のまとめ

POST HTTP Request

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

$nc -l 1234
  • Getのコードとの差はHTTPMethodとHTTPBodyのプロパティの値だけ
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化する部分くらい
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

How to POST JSON data using NSURLSession in swift

75
78
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
75
78

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?