【问题标题】:SerializationFailure error while posting data with Alamofire使用 Alamofire 发布数据时出现 SerializationFailure 错误
【发布时间】:2017-06-12 01:39:55
【问题描述】:

我正在尝试使用 Alamofire 将一些文本数据和图像保存到服务器,但出现以下错误:

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "字符 0 周围的值无效。" UserInfo={NSDebugDescription=字符 0 周围的值无效。}))

我的代码:

internal func postContent(forApi Name:String, image:UIImage?, withData payload:[String: String], success: ((_ response:[String: AnyObject])->Void)?, failure: ((Error)->Void)?) {
    //create Alamofire request
    //if everything was fine call success block with people array passed into it
    //if failure occurred, call failure block with error.
    if(isConnectedToNetwork()){
        let url = SharedConstants.baseURL+Name
        print("url "+SharedConstants.baseURL+Name)

        Alamofire.upload(multipartFormData: { (multipartFormData) in
            if let img = image {
                multipartFormData.append(UIImageJPEGRepresentation(img, 0.5)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
            }

            for (key, value) in payload {
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }
        }, to: url, method: .post , headers:nil, encodingCompletion: { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.responseJSON(completionHandler: { (response) in
                    print(response.request)  // original URL request
                    print(response.response) // URL response
                    print(response.data)     // server data
                    print(response.result)   // result of response serialization

                    if let JSON = response.result.value {
                        print(JSON)
                        success!(JSON as! [String: AnyObject])
                    }
                    else{
                        failure!(ErrorType.noRecordFound)
                    }
                })
            case .failure(let error):
                print(error)
            }
        })
    }
    else{
        failure!(ErrorType.internetNotWorking)
    }
}

提前致谢

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    检查 url 中的路径可能是您缺少某些文件夹。

    【讨论】:

      【解决方案2】:

      前端发送参数:

       {
      "delivery_method": [{
          "vehicle_type": "walk",
          "vehicle_id": "1",
          "vehicle_color": "",
          "vehicle_brand": "",
          "vehicle_image": "",
          "vehicle_number": "",
          "mode_type": "1",
          "vehicle_model": ""
      }, {
          "vehicle_type": "scooter",
          "vehicle_id": "4",
          "vehicle_color": "",
          "vehicle_brand": "",
          "vehicle_image": "",
          "vehicle_number": "",
          "mode_type": "1",
          "vehicle_model": ""
      }]
      }
      

      当我像 JSON.parse(params[:delivery_method]) 这样解析 JSON 时会抛出错误。所以我们可以为json创建一个参数。

      data=JSON.parse(params[:delivery_method].to_json) # no exception.
      

      【讨论】:

        【解决方案3】:
        let headers:HTTPHeaders = ["Authorization": "Bearer " + token2Save]
        let moreheaders:Parameters = ["Dropbox-API-Arg": ["path":sourcePath]]
        
        Alamofire.request("https://content.dropboxapi.com/2/files/download", parameters: moreheaders, encoding: URLEncoding(destination: .queryString), headers: headers).responseJSON { feedback in
                guard feedback.result.value != nil else {
                    print("Error: did not receive data", print("request \(request) feedback \(feedback)"))
                    return
        

        URLEncoding(destination: .queryString), headers: headers).responseJSON

        Replace responseJSON with responseString and check your response  from webservice.. it will lead to get the error line.
        

        参考:

        https://stackoverflow.com/a/43041931/5215474

        将 responseJSON 替换为 responseString 并检查您的响应 webservice..会导致报错行。

        【讨论】:

        • 感谢您的帮助“将 responseJSON 替换为 responseString 并检查您来自 web 服务的响应。它会导致出现错误行。”这对我有帮助
        【解决方案4】:

        iOS 代码正确,后端代码有问题。 json 没有正确形成。我更正了后端的 json 格式,它开始正常工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-23
          • 2012-12-08
          • 2012-11-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多