“ JSON写入(UIImage)中的类型无效” Alamofire API请求

时间:2019-08-15 12:25:08

标签: swift uiimageview alamofire

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

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接收到json主体参数,其中的profilePic已关闭在运行此文件时键入文件,这会给我一个错误,提示'Invalid type in JSON write (UIImage)'。theres也是一个terminating with uncaught exception of type NSException错误。我在做什么错以及如何解决?

1 个答案:

答案 0 :(得分:0)

您不能使用上传图片

"profilePic": uploadedProfileImage

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

upload image to server using 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)"