Alamofireでmultipart/form-dataをパラメータ付きでPostしてみた。(Swift3.0/Alamofire (4.0.1))


Just in case I forget how to use lol
Basically it is so simple, you just need to add "multipartFormData.append()".

Additional Requirement: Reorder if you would like to post many data (more than 2) because Alamofire automatically sorts post params.

Purpose

Personal Note

Development Environment

  • OS X El Captain 10.11.2
  • Xcode Version 8.0

Language

Swift 3.0
Alamofire 4.0.1

Source Code

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                self.addImageData(multipartFormData: multipartFormData,image: self.yourUIImage)

                // If you need to post many data, you need to sort with key.
                if let data = "LawQiita".data(using: String.Encoding.utf8) {
                    multipartFormData.append(data, withName: "yourPostData")
                }

                }
            },
            to: getUrl(),
            headers: getHeader(),
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        print (response)
                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
            }
        )
    private func addImageData(multipartFormData: MultipartFormData, image: UIImage!){
        var data = UIImagePNGRepresentation(image!)
        if data != nil {
            // PNG
            multipartFormData.append(data!, withName: "targetImage",fileName: "targetImage", mimeType: "image/png")
        } else {
            // jpg
            data = UIImageJPEGRepresentation(image!, 1.0)
            multipartFormData.append((data?.base64EncodedData())!, withName: "targetImage",fileName: "targetImage", mimeType: "image/jpeg")
        }

    }