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)
}
}