Alamofire 4.0和Swift 3.0无法获得responseJSON结果

时间:2016-11-20 14:07:00

标签: swift3 alamofire

我可以问一下肝脏吗?尝试.get从.responseJSON获得结果,但在响应中收到失败。

 func performRequest(_ method: HTTPMethod, requestURL: String, params: [String: AnyObject], comletion: @escaping (_ json: AnyObject?) -> Void) {

        Alamofire.request(requestURL, method: .get, parameters: params, encoding: JSONEncoding.default)
          .responseJSON { response in
                print(response)

                if let status = response.response?.statusCode {
                    switch(status){
                    case 201:
                        print("example success")
                    default:
                        print("error with response status: \(status)")
                    }
                }

                print("data:", response.data ?? "no data")  
                print("result:", response.result)

                if let result = response.result.value {
                    let JSON = result as! NSDictionary
                    print("JSON:",JSON)
                    comletion(JSON)
                }
                comletion(nil)

             }
    }

我的回答是:

data: 66809 bytes
result: FAILURE
json: 

我还尝试使用其他类型的响应,例如.responseData但由于某种原因无法解析。

let json = JSON(data: response.data!) //getting nil

由于

1 个答案:

答案 0 :(得分:4)

试试这个,

func performRequest(_ method: HTTPMethod, requestURL: String, params: [String: AnyObject], comletion: @escaping (_ json: AnyObject?) -> Void) {

   Alamofire.request(requestURL, method: .get, parameters: params, headers: nil).responseJSON { (response:DataResponse<Any>) in
            print(response)

    switch(response.result) {
    case .success(_):
        if let data = response.result.value{


            print("YOUR JSON DATA>>  \(response.data!)")
             comletion(nil)

        }
        break

    case .failure(_):
        print(response.result.error)

        comletion(nil)
        break

    }
    }
}