xcode – 如何在Swift中使用Alamofire上传使用参数的图像

我正在用swift开发一个iPhone应用程序.我使用Alamofire framework处理http请求.我使用Alamofire.request进行POST,GET等等:

Alamofire.request(.POST, myURL , parameters: ["a": "1", "b" : "2" ])
        .response { (request, response, data, error) in
}  

而我使用Alamofire.upload将镜像上传到服务器上:

Alamofire.upload(.POST, uploadURL , fileURL)

两者都可以完美地工作,但是现在我想上传一个图像并发送一些参数,我的内容类型应该是multipart / form-data,而Alamofire.upload不接受参数.

关于这个问题,关于这个问题的另外两个问题就是swift,first one没有使用Alamofire(而且真的,为什么不这样),而在second one,mattt(Alamofire Developer)引用了使用编码参数.

我检查了他的例子,但仍然无法弄清楚如何做到这一点.

请问有人能帮我解决这个问题吗?

谢谢! 🙂

你可以使用Alamofire 3.0下面的代码

func uploadImageAndData(){
    //parameters
    let gender    = "M"
    let firstName = "firstName"
    let lastName  = "lastName"
    let dob       = "11-Jan-2000"
    let aboutme   = "aboutme"
    let token     = "token"

    var parameters = [String:AnyObject]()
    parameters = ["gender":gender,
                  "firstName":firstName,
                  "dob":dob,
                  "aboutme":about,
                  "token":token,
                  "lastName":lastName]

    let URL = "http://yourserviceurl/"
    let image = UIImage(named: "image.png")

    Alamofire.upload(.POST, URL, multipartFormData: {
        multipartFormData in

        if let imageData = UIImageJPEGRepresentation(image, 0.6) {
            multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png")
        }

        for (key, value) in parameters {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }
    }, encodingCompletion: {
        encodingResult in

        switch encodingResult {
        case .Success(let upload, _, _):
            print("s")
            upload.responseJSON { 
                response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
            }
        case .Failure(let encodingError):
            print(encodingError)
        }
    })
}
http://stackoverflow.com/questions/26497725/how-to-upload-image-with-parameters-using-alamofire-in-swift

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:xcode – 如何在Swift中使用Alamofire上传使用参数的图像