使用Alamofire上传图片以及其他字符串数据

时间:2015-09-15 08:56:02

标签: ios swift swift2 alamofire

到目前为止,我一直在使用下面的代码将配置文件图片数据上传到服务器。

Alamofire.upload(.POST,
    URLString: "https://example.com/api/v1/users/profile_pic.json?auth_token=\(auth_token)",
    multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(data: imageData, name: "avatar", fileName: "avatar_img.png", mimeType: "image/png")
    },
    encodingCompletion: { encodingResult in

        switch encodingResult {
            case .Success (let upload, _, _):
                upload.responseJSON { request, response, data, error in

                // Do whatever 

                } 
            case .Failure (let encodingError):
        }

    })

但是现在我还需要将用户的其他详细信息上传到服务器,例如first_name和last_name。我应该如何在一个请求中连同图片数据一起做?

1 个答案:

答案 0 :(得分:0)

这就是你如何做到的

    Alamofire.upload(.POST, path, headers: self.predefinedHeaders, multipartFormData: { multipartFormData in

                    multipartFormData.appendBodyPart(data: imageData, name: "avatar", fileName: "avatar_img.png", mimeType: "image/png")

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

                    }, encodingCompletion:{ encodingResult in
                     //your handling
                    })