Search code examples
swift3alamofire

Alamofire 4.0 and Swift 3.0 can't get responseJSON result


can I ask about hepl. Trying to .get result from .responseJSON but receiving failure in response.

 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)

             }
    }

My response is:

data: 66809 bytes
result: FAILURE
json: 

I also tried to use other types of response like .responseData but can not parse for some reason.

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

Thanks


Solution

  • Try this,

    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
    
        }
        }
    }