我正試圖在我的應用程式中連接圖片上傳。我正在使用Alamofire和Alamofire中的multipartFormData功能來實作這一目標。
我寫了一個函式來上傳這個圖片和其他屬性。
func savePreferences(parameters: [String:Any], image: UIImage, completion: @escaping (Response? , Error? -> Void) {
let url = "http://localhost:3000/users/3b4e124d-3b3c-4c71-8e05-013e461c2892"/span>
let imgData = image.jpegData(compressionQuality: 0.5)!
AF.upload(multipartFormData: { multipartFormData in.upload(multipartFormData:).
multipartFormData.append(imgData, withName: "profile_imgname", fileName: "ProfilePic_(UserDefaults.standard. string(forKey: "user_id") ? ").jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to: url, method: .patch) { (result) in
switch 結果 {
case .success(let upload)。
upload.responseJSON { response in.
if let err = response.error {
failure(err)
回傳。
}
completion(response.result.value)
}
case .failure(let error):
print("上傳錯誤。(error.localizedDescription)")
}
}
}
在最后的switch陳述句中,在case .success和case .failure中,我收到以下錯誤:
型別'URLRequest'沒有成員'failure'
。
型別'URLRequest'沒有成員'success'
。
我使用了現有的Stack Overflow資源來了解這個multipartFormData是如何作業的,似乎它們在一定程度上遵循了這個格式。
請看下文:
使用 Alamofire 發送帶有 MultipartFormData 的 POST 引數,在 iOS Swift 中
為什么我收到的圖片都被洗掉?
為什么我得到的錯誤是URLRequest沒有成員失敗,我如何才能糾正這個問題?
uj5u.com熱心網友回復:
Alamofire 5.0遷移檔案是這樣說的:
MultipartFormData的API已經改變,創建和上傳MultipartFormData的頂層上傳方法已經更新,以匹配其他請求API,所以不再需要處理多部分編碼的結果。
(https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire 5.0 Migration Guide.md)
你所使用的代碼看起來是早期版本的。在5.0中,尾部閉合使用URLRequest作為其引數(解釋了你所看到的錯誤)。
使用指南(https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md)提供了這樣一個上傳多部件表單資料的示例:
AF.upload(multipartFormData: { multipartFormData in.
multipartFormData.append(Data("one".utf8), withName: "one")
multipartFormData.append(Data("wo".utf8), withName: "two")
}, to: "https://httpbin.org/post")
.responseDecodable(of: HTTPBinResponse.self) { 回應 in.
debugPrint( response)
}
(HTTPBinResponse是一個Decodable的例子,你可以用你自己的代碼替換)。
除了responseDecodable之外,看起來你還可以使用responseJSON、responseData、responseString等。
注意,所有這些都是在呼叫的結尾)之后附加一個.--而不是作為一個尾部閉合。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/331995.html
標籤:
