iosswiftafnetworking-3

Indicated 'Anyobject' is not a subtype of 'NSProxy' when using AFNetworking


I'm using AFNetworking to retrieve weather info form openweathermap API.

let manager = AFHTTPSessionManager()
    manager.requestSerializer = AFJSONRequestSerializer()
    let url = "http://api.openweathermap.org/data/2.5/weather"
    let params = ["lat": latitude,"lon": longitude,"cnt": 0]

    manager.get(url, parameters: params,
                success: {(operation: URLSessionDataTask,responseObject: AnyObject!) in print("JSON" + responseObject.description!) },
                failure: {(operation: URLSessionDataTask?,error: Error) in print(error.localizedDescription)}
    )

highlighting at responseObject.description indicated that 'Anyobject' is not a subtype of 'NSProxy' If remove .description the error will disappear. platform:xcode 8.3.2 swift:3

'Anyobject' is not a subtype of 'NSProxy'


Solution

  • First on of all the get method you are using is a deprecated one (I assume you have newest AFNetworking version). Please use the new one this way:

    let manager = AFHTTPSessionManager()
    manager.requestSerializer = AFJSONRequestSerializer()
    let url = "http://api.openweathermap.org/data/2.5/weather"
    let params = ["lat": 5.0,"lon": 5.0,"cnt": 0]
    manager.get(url, parameters: params, progress: nil, success: { (operation, responseObject) in
        if let responseObject = responseObject {
            print(responseObject)
        } else {
            print("There is no response object") //assume parsing error for JSON
        }
    }) { (operation, error) in
        print(error.localizedDescription)
    }
    

    As the last tip: if you are using Swift, better use Alamofire: https://github.com/Alamofire/Alamofire

    It supports lots of nice features coming from Swift and much nicer error handling. For example Alamofire treats parsing error as real errors and calls failure block, not success block like ANetworking. Also allows you to easily integrate some JSON parsing libs like SwiftJSON https://github.com/SwiftyJSON/SwiftyJSON