Search code examples
iosiphoneswiftweb-servicesalamofire

Alamofire API request is getting failed with responseSerializationFailed in swift 3


I am calling normal API call with Alamofire, And I am not passing any data with that in networking manager class.

My Networking class is

func executeGetRequest(url:String,requestVC:UIViewController,completionHandler:@escaping (_ responseObject:Any?) -> Void!,failureHandler:@escaping (_ connectionError:NSError?) -> Void!){

    //Checking internet alert
    if !self.isConnectedToInternet(){
        // requestVC.showAlert(kText_AppName, message: kText_NoInternet)
        return
    }

    requestVC.showLoader()
    Alamofire.request(url).responseJSON {
        (response:DataResponse) in

        requestVC.removeLoader()

        switch(response.result) {
        case .success(_):
            if response.result.value != nil{
                completionHandler (response.result.value)
            }
            break

        case .failure(let error):
            failureHandler (error as NSError?)
            break

        }
    }
}

and i am calling it from my main class

kNetworkManager.executeGetRequest(url: kAppAccessTokenURL, requestVC: self, completionHandler: {
     (responseObject) -> () in
          print("responseObject:\(responseObject!)")


      }, failureHandler: {(error)-> () in
          print("response object:\(error!)")
          self.showAlert(message: (error?.description)!, title: kText_AppName)
          if error?._code == NSURLErrorTimedOut {
                //timeout here
                self.showAlert(message: kText_timeout, title: kText_AppName)
           }
      })

Its getting always request fail and showing error as responseSerializationFailed

if I call directly in Main Class without manager class like

Alamofire.request(kAppAccessTokenURL).responseString { response in

I am able to getting response, can anyone suggest me where getting wrong in Network class.


Solution

  • Here you

    Alamofire.request(kAppAccessTokenURL).responseString
    

    and there

     Alamofire.request(url).responseJSON
    

    look to that

         let jsonText = "{\"first_name\":\"Sergey\"}"
            var dictonary:NSDictionary?
    
            if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
    
                do {
                    dictonary =  try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
    
                    if let myDictionary = dictonary
                    {
                         print(" First name is: \(myDictionary["first_name"]!)")
                    }
                } catch let error as NSError {
                    print(error)
                }
            }