获得无效的响应Alamofire

时间:2016-05-04 11:10:21

标签: ios swift afnetworking-3

您好我正在使用Alamofire,但我得到了#34;无效的JSON。"在响应中,我使用了以下代码 -

parametersV = ["username":amrit21@yopmail.com, "password":123456]
let headers = ["Content-Type": "application/json", "x-csrf-token":""]

Alamofire.request(.POST, "https://dev.staffingevolution.com/api/user/login", parameters: parametersV, headers: headers).responseJSON { 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: \(JSON)")
  }
}

2 个答案:

答案 0 :(得分:3)

  

我解决了它

MyEnum

编码您没有对JSON请求进行编码是一个问题。使用编码:.JSON

答案 1 :(得分:0)

有时,当响应时没有正确的JSON时,代码段.responseJSON { response in会抛出异常,我们无法看到接收到的响应类型。在这种情况下,我们可以在转换为.responseJSON { response in之前将其打印到控制台 以下是完整示例

public  func deleteImage(_ photoId: Int) {

    let requestURL = URL(string: APPURL.BASE_API_URL + "postApi/deletePostPhoto")!
    let paramDict: [String: String] = ["photoId": String(photoId), "accessKey": APP_DELEGATE.loggedInUser.accessKey, "language":APP_DELEGATE.language.lowercased()]


    Alamofire.upload(
        multipartFormData: { multipartFormData in
            for (key, value) in paramDict {
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }
    },
        usingThreshold:UInt64.init(),
        to: requestURL ,
        method:.post,
        headers:nil,
        encodingCompletion: { encodingResult in

            switch encodingResult {
            case .success(let upload, _, _):

                // this is point where we can get actual response recieved from server, it may have some html , xml or anything

                upload.responseData(completionHandler: { response in

                    print(response)
                    let responseData = String(data: response.data!, encoding: String.Encoding.utf8)
                    print("responseData=",responseData ?? "none")
                })

                // if there is proper JSON recieved it will be executed otherwise it will fall in failure
                upload.responseJSON { response in

                    if((response.result.value) != nil) {

                        let swiftyJsonVar = JSON(response.result.value!)
                        print("response JSON: ",swiftyJsonVar)


                    }
                    else {

                        let error = response.error
                        print(error?.localizedDescription ?? "")

                    }

                }

            case .failure(let encodingError):

                print(encodingError.localizedDescription)

            }
    })

}