23
21

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.

AlamofireでMultipartFormDataをパラメータ付きでポストする

Last updated at Posted at 2015-09-02

Alamofire v1.3.1 時点

AlamofireにMultipartFormDataが実装されたが、同時にパラメータを渡す方法がわからなかった。

もっと簡潔なやり方があるのかもしれないが、値をNSDataに変換してmultipartFormData.appendBodyPart(data:name:)で追加してやれば、とりあえずパラメータを追加することはできるようだ。

let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png")!

Alamofire.upload(
    .POST,
    URLString: "http://httpbin.org/post",
    multipartFormData: { (multipartFormData) in
        // file upload
        multipartFormData.appendBodyPart(fileURL: fileURL, name: "uploadFile")

        // stringVal=hoge
        if let data = "hoge".dataUsingEncoding(NSUTF8StringEncoding) {
            multipartFormData.appendBodyPart(data: data, name: "stringVal")
        }

        // intVal=10
        if let data = String(10).dataUsingEncoding(NSUTF8StringEncoding) {
            multipartFormData.appendBodyPart(data: data, name: "intVal")
        }
    },
    encodingCompletion: { (encodingResult) in
        switch encodingResult {
        case .Success(let upload, _, _):
            upload.responseJSON { request, response, JSON, error in
                println(JSON)
            }
        case .Failure(let encodingError):
            println(encodingError)
        }
})
23
21
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
23
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?