'Invalid type in JSON write (UIImage)' 阿拉莫火 API 请求



我正在尝试使用alamofire将图像发送到api这是我得到的:

var uploadedProfileImage: UIImage = UIImage()
let body: Parameters = [
"profilePic": uploadedProfileImage,
"name": "John Doe"
]
Alamofire.request(BASE_URL",method: .post,parameters: body,encoding: JSONEncoding.default).responseData { response in
debugPrint("All Response Info: (response)")
if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: (utf8Text)")
}
}

所以这是我正在使用的代码uploadProfileImage它有一个用户从库中挑选的图像,我的api收到一个jsonbody 参数,其中它有一个 profilePic 当我运行它时它是关闭类型文件,它给我一个错误说'Invalid type in JSON write (UIImage)'.theres 也是一个terminating with uncaught exception of type NSException错误。 我做错了什么以及如何解决它?

您无法使用 上传图片

"profilePic": uploadedProfileImage

因为它用于可编码的类型,例如字符串,因此您需要

使用Alamofire将图像上传到服务器

func uploadImageAndData(_ url:String,parameters1:Parameters,headers1:HTTPHeaders,images:[UIImage]){

Alamofire.upload(multipartFormData: { multipartFormData in
// import image to request
var i=0
for imageData in images {
//  multipartFormData.append(self.resizeImage(image: imageData, targetSize: CGSize(width: 400, height:
multipartFormData.append(imageData.pngData()!, withName: "image", fileName: "image"+".jpeg", mimeType: "image/jpeg")
i += 1

}
for (key, value) in parameters1 {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
} ,to: url,method:.post,
headers:[:],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: (Progress.fractionCompleted)")
//SwiftSpinner.show(progress: Progress.fractionCompleted*100, title: "تحميل")
})
upload.responseJSON { response in
switch response.response?.statusCode {
case 200 :

break
case 400 :

break
case 401 :

break

case 302 :

break
case 500 :

break
default: break

}
}
return
case .failure(let encodingError):
}
})
}

var head = [String:Any]()
head["Accept"]="application/json"
head["Authorization"] = "Bearer (tokenIfExists)"