Swift 4 Alamofire 和编码 UIImage 的问题
Posted
技术标签:
【中文标题】Swift 4 Alamofire 和编码 UIImage 的问题【英文标题】:Trouble with Swift 4 Alamofire and encoding UIImage 【发布时间】:2018-11-29 04:35:48 【问题描述】:使用 post 和 Swift 4、Xcode 10 和 Alamofire 将 UIImage 发送到我的服务器 API 时遇到问题。 我在 Xcode 中遇到的错误是无法写入数据,因为它的格式不正确。提前感谢您的帮助。
func saveImage(image: UIImage?)
guard let imageToSave = image else
return
guard let imageData = imageToSave.pngData() else
return
let jsonUrlString = "http://192.168.1.5:8080/json/\(imageData)/uploadUserImage"
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do
let jsonData = try encoder.encode(imageData)
postImageAF(url: jsonUrlString, data: jsonData) (err, result) in
if(err != nil)
print("error in postWithAlamofire \(err!.localizedDescription)")
return
print("result in postWithAlamofire \(result ?? "no result")")
catch
print(error.localizedDescription)
print("error in postWithAlamofire \(error.localizedDescription)")
func postImageAF(url: String, data: Data, callback: @escaping (Error?, String?) -> Void)
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = data
Alamofire.request(request).responseData response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
【问题讨论】:
【参考方案1】:如果您在服务器端使用 multipartFormData 类型,请按照以下代码上传您的图片:
let imgData = newImage.jpegData(compressionQuality: 0.2)!
let imageName = "testImage.jpg"
Alamofire.upload(multipartFormData: multipartFormData in
multipartFormData.append(imgData, withName: "file",fileName: imageName, mimeType: "image/jpeg")
, to:urlString) (result) in
switch result
case .success(let upload, _, _):
upload.uploadProgress(closure: (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
)
upload.responseJSON response in
print("response.result :\(String(describing: response.result.value))")
case .failure(let encodingError):
print(encodingError)
【讨论】:
以上是关于Swift 4 Alamofire 和编码 UIImage 的问题的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Alamofire Swift 4 在 JSON 编码中传递数据
URL编码参数中的布尔值在Swift3中使用Alamofire编码为0和1
将可编码结构编码为 Alamofire POST 参数 - Swift
Swift 3 的 ObjectMapper 和 Alamofire 问题 Alamofire 4 的 Alamofire 版本