Search code examples
swift3afnetworkingswift2

Swift3: AFNetworking Issues converting failure Block from Swift2 to Swift3


I am converting my Swift2 code to Swift3.

Code in Swift2

manager.post(url, parameters: dict,
      success: { (operation: AFHTTPRequestOperation?, responseObject: Any?) in
          self.removeActivityIndicator()                    
          
          if let jsonDict = self.parseJSON(responseObject) {
              callback(jsonDict)
          }
      },
      failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
          self.removeActivityIndicator()
          
          print("Error: " + error.localizedDescription)
          var dict = error.userInfo
          dict["error"] = error.localizedDescription
          if let jsonDict = dict as? Dictionary<String, AnyObject> {
              callback(jsonDict)
          }
      }
  )

In Failure section I got the following error message,

Cannot convert value of type '(AFHTTPRequestOperation!, NSError!) -> ()' to expected argument type '((AFHTTPRequestOperation?, Error?) -> Void)!'

When I convert failure: { (operation: AFHTTPRequestOperation!, error: NSError!) to failure: { (operation, error)

I got and error on line

var dict = error.userInfo

as 'Value of type Error has no member UserInfo'


Solution

  • . . Use Alamofire as Larme advised or explore some other service. Alamofire is same as AFNetworking and very flexible. You will integrate with a minor change in your code. AFNetworking is not much supported by Swift3,4.