Search code examples
swiftalamofire

AlamoFire response back in JSON failing Swift


I have the following code:

    let request = AF.request(GET_SEARCH_API)
    
    request.responseJSON { (data) in
        print("SEARCHED RESULTS: \(data)")
        let JSON = data as! NSDictionary
    }

It is failing on this line let JSON = data as! NSDictionary

enter image description here

What am I doing wrong here?


Solution

  • responseJSON, which is deprecated and shouldn't be used, doesn't return the data or JSON representation directly. That closure receives a DataResponse value that has various properties for the various parts of the response.

    You can print it directly, but you can't cast it to anything, nor should you ever really need to do so in Swift. I suggest reading the Alamofire documentation to understand the API, and investigate responseDecodable to decode JSON responses into proper Swift types.