LoginSignup
31
30

More than 5 years have passed since last update.

[Swift] Alamofireのサンプルコード

Last updated at Posted at 2014-12-02

AlamoFireの基本的な使い方のサンプルコードをいくつか。備忘録。

GET

受信中のバイト数の表示付き。

Alamofire.request(.GET, "http://example.com")
  .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
    println(totalBytesRead)
  }
  .response { (request, response, data, error) in
    println(data) 
  }

POST

let param = [
   "param1":  "hoge",
   "param2":  "moge",
]

Alamofire.request(.POST, "http://example.com", parameters: param)

ファイルアップロード

// リソースファイルをアップロード
let fileURL = NSBundle.mainBundle().URLForResource("data", withExtension: "zip")

Alamofire.upload(.POST, "http://example.com", fileURL!)
  .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
    println(totalBytesWritten)
  }
  .response { (request, response, data, error) in
    println(data) 
  }

タイムアウト付きGET

var alamofireManager : Alamofire.Manager?

func some(){
  let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  configuration.timeoutIntervalForResource = 2 // seconds

  self.alamofireManager = Alamofire.Manager(configuration: configuration)
  self.alamofireManager!.request(.GET, "http://example.com/")
    .response { (request, response, data, error) in
      println(data) 
    }
}

参考文献

31
30
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
31
30