Alamofire 向 API 'NSInvalidArgumentException' 发送请求

Posted

技术标签:

【中文标题】Alamofire 向 API \'NSInvalidArgumentException\' 发送请求【英文标题】:Alamofire sending a request to an API 'NSInvalidArgumentException'Alamofire 向 API 'NSInvalidArgumentException' 发送请求 【发布时间】:2019-08-16 08:51:24 【问题描述】:

我正在使用此代码将图像和文本发送到 api:

    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: uploadedProfileImage, targetSize: CGSize(width: 200, height: 200)
                multipartFormData.append(imageData.pngData()!, withName: "profilePic", fileName: "profileimage"+".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("showuing upload progress")
                    print("Upload Progress: \(Progress.fractionCompleted)")
                    //SwiftSpinner.show(progress: Progress.fractionCompleted*100, title: "تحميل")
                )
                upload.responseJSON  response in

                    print(response.response?.statusCode as Any)

                    if let data = response.result.value, let utf8Text = String(data: data as! Data, encoding: .utf8) 
                        print("New Func Data: \(utf8Text)")
                    
                    switch response.response?.statusCode 
                    case 201 :
                        print("Success")
                        break
                    case 413 :
                        print("Post too large")
                        break
                    case 200 :
                        print("200")
                        break
                    case 400 :
                        print("400")
                        break
                    case 401 :
                        print("401")
                        break
                    case 302 :
                        print("302")
                        break
                    case 500 :
                        print("500")
                        break
                    default: break
                    
                
                return
            case .failure(let encodingError): break

            
        )
    

我得到了这些数据:

let address: Parameters = [
          "location" : addressField.text!,
          "locationLat" :pickedLocationLat,
          "locationLong" :pickedLocationLong
     ]                           

  let body: Parameters = [
          "name": "Sample Name",
          "email": "test@test.com",
          "password": "test123",
         "address": address
    ]

我正在使用此代码访问该函数

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


uploadImageAndData(BASE_URL", parameters1: body, headers1: head as! HTTPHeaders, images: [uploadedProfileImage])

这段代码抛出了类似的错误

Terminating app due to uncaught exception 'NSInvalidArgumentException'
reason: '-[_TtGCs26_SwiftDeferredNSDictionarySSP__$ dataUsingEncoding:]: unrecognized selector sent to instance 0x6000015bed00'
terminating with uncaught exception of type NSException

我不知道是什么导致了这个问题,api 需要一个 json 正文和一个 content-typeapplication/json 我厌倦了删除body参数的所有内容,除了名称尝试只发送名称,当我这样做时,图像上传成功,但它仍然给我这个错误,所以请帮我解决这个问题。

【问题讨论】:

我所知道的编码存在一些问题。 multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key) 这行看起来很可疑。 【参考方案1】:

您需要将值设置为不加倍的字符串

let address: Parameters = [
      "location" : addressField.text!,
      "locationLat" :"\(pickedLocationLat)",
      "locationLong" :"\(pickedLocationLong)"
]

【讨论】:

谢谢这个工作你也看看这个问题吗***.com/questions/57636368/…

以上是关于Alamofire 向 API 'NSInvalidArgumentException' 发送请求的主要内容,如果未能解决你的问题,请参考以下文章

在后台接收静默推送时无法向 Alamofire 发出请求

如何从 API 发送错误

使用 Alamofire 在 HTTP Body 中发送数据

Alamofire 发布请求未执行

为啥没有网络连接时 Alamofire 需要这么长时间才能超时?

如何暂停应用程序直到使用 Alamofire 下载 json 数据?