しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

Swift時代の定番通信ライブラリのAlamofireを使ってみる #Swift4対応

2017/10/6追記: Swift4対応

定番ライブラリのAlamofireを試してみました。

github.com

CocoaPodsでのインストールは下の通りです。

use_frameworks!

pod 'Alamofire'

Carthageでのインストールは下の通りです。
折角対応しているので今回はCarthageでインストールしました。

github "Alamofire/Alamofire"

JSONデータをGetで受け取る

JSONデータをGet通信で取得する方法は下の通りです。
requestメソッドでリクエストを送って、responseJSONでデータを取得します。

import Alamofire

Alamofire.request("http://localhost:3000/users.json", method: .get, parameters: ["foo": "var"]).responseJSON(completionHandler: { response in
    print(response.value) // レスポンスがディクショナリ形式で入っている
})

レスポンスをJSON以外で受け取る

レスポンスをJSON以外で受け取りたい場合はresponseJSONを別メソッドに置き換えます。
例えばStringとして受け取りたい場合はresponseStringを使います。
データはJSONの時と同様にresponse.valueで受け取れます。

Alamofire.request("http://localhost:3000/users.json", method: .get, parameters: ["foo": "var"]).responseString(completionHandler: { response in
    print(response.value)
})

GET以外の通信

GET以外を使いたい場合は第二引数を入れ替えます。
OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECTの9種類に対応しています。

Alamofire.request("http://localhost:3000/users.json", method: .post, parameters: ["foo": "var"]).responseString(completionHandler: { response in
    print(response.value)
})

headerに値をセットする

headerへの値のセットは下の通りです。

let headers = [
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
    "Content-Type": "application/x-www-form-urlencoded"
]
        
Alamofire.request("http://localhost:3000/users.json", method: .get, parameters: ["foo": "var"], headers: headers).responseString(completionHandler: { response in
})

ファイルのアップロード

ファイルのアップロードにも対応しています。
アップロードをする場合はrequestメソッドの代わりにuploadを使います。

ダウンロードをしたい場合はrequestの代わりにdownloadを使うようです。

if let url = Bundle.main.url(forResource: "image", withExtension: "png"), let data = try? Data(contentsOf: url) {
    Alamofire.upload(data, to: "http://localhost:3000/hoge")
}

ベーシック認証

ベーシック認証にはauthenticateを使います。

Alamofire.request("http://localhost:3000/users.json", method: .get, parameters: ["foo": "var"], headers: headers).authenticate(user: "user", password: "password").responseString(completionHandler: { response in
})