Search code examples
swift3swift2alamofire

Migrating Alamofire.Request extension from Swift 2 to Swift 3


I'm trying to migrate an extension to Alamofire.Request but am getting the error Cannot call value of non-function type 'HTTPURLResponse?'.

I know the compiler thinks I'm referring to the member response and not the function.

I've already replaced Request.JSONResponseSerializer with DataRequest.jsonResponseSerializer.

Can anyone see what I'm missing?

extension Alamofire.Request {
    public func responseSwiftyJSON(_ queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler:  @escaping (NSURLRequest, HTTPURLResponse?, SwiftyJSON.JSON, Error?) -> Void) -> Self {
        return response(responseSerializer: Alamofire.DataRequest.jsonResponseSerializer(options: options)) { response in
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                var responseJSON: JSON

                if response.result.isFailure {
                    responseJSON = JSON.null
                } else {
                    responseJSON = SwiftyJSON.JSON(response.result.value!)
                }

                dispatch_async(queue ?? dispatch_get_main_queue(), {
                    completionHandler(self.request!, self.response, responseJSON, response.result.error)
                })
            }
        }
    }
}

Solution

  • I'm not sure if this is compatible with older versions, but I suggest you rewrite your extensions as this:

    extension DataRequest {
        public func responseSwiftyJSON(queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler:  @escaping (URLRequest?, HTTPURLResponse?, SwiftyJSON.JSON, Error?) -> Void) -> Self {
            return responseJSON(queue: queue, options: options) {
                let responseJSON: JSON
                switch result {
                case let .success(json): responseJSON = JSON(json)
                case .failure: responseJSON = JSON.null
                }
    
                completionHandler(request, response, responseJSON, error)
            }
        }
    }