【问题标题】:Uploading an image with Alamofire not succeeding使用 Alamofire 上传图像不成功
【发布时间】:2019-05-02 07:26:53
【问题描述】:

我正在尝试使用主体参数 img(图像)和 id(可以是任何数字)向端点发出 POST 请求。

这在 Postman 中有效(除非id 丢失,否则服务器永远不会响应失败/成功):

但是,在 iOS 应用方面:

class func postPreviewImage(operaID: Int, image: UIImage, completion: @escaping () -> Void) {
    let URL_CORDINATE = "http://artaugmentedreality.com/api/postpreview/"
    print("Trying to post a preview of opera with ID:", operaID)

    guard let imgData = image.jpegData(compressionQuality: 0.2) else {
        print("Error while retrieving image data")
        return
    }

    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "img", fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "image/jpeg")
        multipartFormData.append(operaID.data, withName: "id")
    },
                     to: URL_CORDINATE,
                     method: .post)
    { (result) in
        print("Result of Alamofire call is", result)

        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })
        case .failure(let encodingError):
            print("Error while uploading image:", encodingError)
        }
    }
}

extension Int {
    var data: Data {
        var int = self
        return Data(bytes: &int, count: MemoryLayout<Int>.size)
    }
}

它正在上传,但不知何故服务器没有收到它。我的请求代码可能有问题吗?我得到一个:

Error copying matching creds.  Error=-25300, query={
atyp = http;
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = http;
"r_Attributes" = 1;
sdmn = "artaugmentedreality.com";
srvr = "artaugmentedreality.com";
sync = syna;
}

来自 Alamofire 的错误代码,可能是因为域不是 HTTP。但是,我将该域包含在 info.plist 的允许域列表中:

所以我不知道如何从这里出发。

【问题讨论】:

  • 嗨@Cesare!我已经在stackoverflow.com/questions/50489453/…@给出了答案
  • 谢谢!我看到您将所有参数作为 [String: String] 传递,但是,我的 id 是一个整数。如果我在正文参数中传递整数数据而不是字符串数据,你认为这重要吗?
  • 我完全不知道,但我认为这可能会导致问题......
  • 在 plist 文件中看不到“允许任意加载”这个键。
  • @ShauketSheikh 现已添加,但没有改变。

标签: ios swift alamofire


【解决方案1】:

您将 ID 参数与图像一起发送。所以尽量使用utf8编码。

 multipartFormData.append(operaID.data(using: .utf8)!, withName: "id")

【讨论】:

  • operaID 是一个整数,所以 data(using:) 不可用。我应该先将 id 转换为字符串吗?
  • 是的,也试试 :)
猜你喜欢
  • 2017-08-23
  • 2017-06-19
  • 2016-12-19
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多