【问题标题】:How to do a multipartFormData upload in Alamofire4?如何在 Alamofire 4 中进行多部分表单数据上传?
【发布时间】:2017-01-16 17:25:19
【问题描述】:

迁移对我来说简直就是一场噩梦。我有这个旧版本的 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 给了我一个错误说“对成员'upload(_:to:method:headers) 的模糊引用”但我不知道我是否可以相信这些错误消息,因为 Alamofire 触发调用并且现在抛出数千错误,一个例子是 encoding: .json 现在是 JSONEncoding.default 但 Xcode 告诉我错误是“函数调用中的额外方法”。所以我尝试了大多数其他错误的解决方案,即切换方法和 url 参数

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

但这也行不通。我应该如何重写它以使用新的 Swift/Alamofire?

【问题讨论】:

标签: ios swift swift3 alamofire alamofireimage


【解决方案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
  }
)

【讨论】:

  • 我应该把headers 参数放在我原来的位置吗?这实际上是我的主要问题
  • 这是upload 函数的可选参数。请参阅github.com/Alamofire/Alamofire/blob/… - 我编辑了答案以包含标题
猜你喜欢
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-18
相关资源
最近更新 更多