如何在Alamofire4上进行multipartFormData上传?

时间:2017-01-16 17:25:19

标签: ios swift swift3 alamofire alamofireimage

迁移对我来说简直就是一场噩梦。我有以前版本的Swift / iOS / Alamofire

中的旧代码
let intVal = 0

Alamofire.upload(.POST, url, headers: ["StringValue": intVal, "StringValue2": "StringValue3"], multipartFormData: { mpfd in
        let image = self.profileImageView.image!
        let imageData = UIImageJPEGRepresentation(image, 0.8)!
        mpfd.appendBodyPart(data: imageData, name: "image", fileName: "custom_image.jpg", mimeType: "image/jpeg")
        }, encodingCompletion: { result in

            switch result {
            case .success(let request, _, _):
                let response = request.response
                print("response from image change: \(response)")
                print("Successfully changed pro pic")
            case .failure/*(let encodingError)*/:
                print("Failed to change pro pic")
            }

    })

但现在Xcode给了我一个错误说"模糊引用成员'上传(_:to:method:headers)"但是我不知道我是否可以信任这些错误消息,因为Alamofire会调用并且现在会抛出数千个错误,例如encoding: .json现在是JSONEncoding.default但是Xcode告诉我错误是& #34;函数调用中的额外方法"。所以我尝试了大多数其他错误的解决方案,即切换方法和url参数

Alamofire.upload(url, method: .post, headers ...)

但这也不起作用。我怎么能重写这个以使用新的Swift / Alamofire?

1 个答案:

答案 0 :(得分:1)

在Alamofire的测试套件中有一个例子:https://github.com/Alamofire/Alamofire/blob/9688b16f0546b97b16c775c75f42b3f4bfacc78e/Tests/UploadTests.swift#L244

guard let image = self.profileImageView.image,
  let imageData = UIImageJPEGRepresentation(image, 0.8) else {
    return
}

Alamofire.upload(
  multipartFormData: { multipartFormData in
    mpfd.append(imageData, withName: "image", fileName: "custom_image.jpg", mimeType: "image/jpeg")
  },
  to: url,
  headers: ["Header": value, "Another_Header": value2],
  encodingCompletion: { result in
    // Whatever
  }
)