LoginSignup
22
15

More than 5 years have passed since last update.

Alamofire4でJsonをPOST、ファイルを multipart/form-data でPOST

Last updated at Posted at 2016-11-24

Alamofire 4.0 で HTTP POST する

ググって出てくる Alamofire のコードは古いバージョンのものが多く出てくるので、
Alamofire 4.0 での HTTP POSTのやり方を整理しました

ハンドリングが簡単でめっちゃ使いやすいです

JSON を POST で送信

この例ではレスポンスをJsonオブジェクトとして受け取るために.responseJSON をレスポンスハンドラーにしてます

JSONをPOSTするサンプル
let url = "http://hoge/fuga"
let headers: HTTPHeaders = [
    "name": "value"
]
let parameters: Parameters = [
    "str_param": "str value",
    "num_param": 0,
    "nested": [
        "nested_param": "value"
    ]
]

Alamofire.request(url,
                  method: .post,
                  parameters: parameters,
                  encoding: JSONEncoding.default,
                  headers: headers)
    .authenticate(user: "user", password: "password")
    .responseJSON { response in

        if
            let json = response.result.value as? [String: Any],
            let prop1 = json["prop1"] as? String
        {
            debugPrint(prop1)
        }

        debugPrint(response)
}

レスポンスを文字列で受け取りたい時は、.responseStringを使いましょう

レスポンスを受け取りたい型に応じてハンドラーが用意されています
https://github.com/Alamofire/Alamofire#response-handling

複数のレスポンスハンドラーをチェーンさせて使うこともできます
https://github.com/Alamofire/Alamofire#chained-response-handlers

ファイルを multipart/form-data で POST

upload を使った場合は、request と違って送信途中の progress を取得できます
それ以外は request とほぼ同じです

ベースはJSONをPOSTする時と似た感じですが、データを送信する処理の前にファイルをエンコードした結果をコールバックで受け取る処理を挟む必要があるので、初めてだとちょっとだけわかりにくいです

multipart/form-dataでファイルをPOSTするサンプル
let fileContent = "file content as string"
let url = "http://hoge/fuga"
let headers: HTTPHeaders = [
    "name": "value"
]

Alamofire.upload(
    multipartFormData: { (multipartFormData) in
        multipartFormData.append(fileContent.data(using: String.Encoding.utf8)!,
                                     withName: "param_name",
                                     fileName: "filename",
                                     mimeType: "multipart/form-data")},
    to: url,
    headers: headers,
    encodingCompletion: { encodingResult in
        // file をエンコードした後のコールバック
        switch encodingResult {
        case .success(let upload, _, _):
            // upload は request の戻り値の DataRequest を継承したオブジェクトなので
            // request と同様にメソッドチェーンしたい項目はこの中で指定できます
            upload
            .authenticate(user: "user", password: "password")
            .uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })
            .responseString { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)

22
15
1

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
22
15