Search code examples
swiftalamofirejsondecoder

Could not cast value of type '__NSDictionaryI' to 'NSData'


I'm trying to decode the following data:

AF.upload(postData!, to: loginUrlString, headers: postmanManager.headers).responseJSON { response in
        switch response.result {
        case .success(let value):
            print(value)
            do {
                let results = try JSONDecoder().decode(User.self, from: value as! Data)
                DispatchQueue.main.async {
                    let id = results.Usuario[0].Id
                    let name = results.Usuario[0].Name

                    let userInfo = UserModel(Id: id, firstName: name)
                    print(userInfo)
                }
            } catch {
            print(error)
            }
        case .failure(let error):
            print(error)
        }
    }

The 'User' object belongs to the following struct:

struct User: Codable {
let Usuario: [UserData]
}

struct UserData: Codable {
let Id: Int
let Name: String
}

I tried looking up the answer and from what I understood, I tried changing value as! Data to value as! [String: Any], but I get another error:

Cannot convert value of type '[String : Any]' to expected argument type 'Data'

What else could I try changing? Thanks for the help!


Solution

  • You are using the wrong response type.

    Replace

    .responseJSON
    

    with

    .responseData
    

    And please name functions and variables with starting lowercase letter.