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

标签 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 body 参数,其中包含 profilePic,当我运行此命令时,它是非类型文件,它给我一个错误,说 'Invalid type in JSON write (UIImage)' .还有一个terminating with uncaught exception of type NSException错误。我做错了什么以及如何解决它?

最佳答案

您无法上传图片

"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)"

关于swift - “JSON 写入 (UIImage) 中的类型无效”Alamofire API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57509627/

相关文章:

ios - 如何比较 if() 结构中的 UIImageView 名称

ios - 无法使用 Alamofire 4.1.0、Xcode 8 和 Swift 3 构建项目 - 没有这样的文件或目录

ios - 如何限制for循环中的网络调用次数?

ios - 如何在 iOS Swift 3 中使用 guard 和 condition?

ios - Kotlin 多平台项目无法从 XCFramework 找到模块

Swift:如何使具有子类返回类型的函数符合协议(protocol),其中父类(super class)被定义为返回类型?

swift - 带参数的 Alamofire GET 请求,-> "extra argument in call"

ios - 如何在 Objective c 中将捕获图像添加到 UITableView

objective-c - UIImageView 的 UIImage 为零

ios - XCode 6.3 Alamofire.swift 文件崩溃