Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

swift - 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!

question from:https://stackoverflow.com/questions/65918071/could-not-cast-value-of-type-nsdictionaryi-to-nsdata

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are using the wrong response type.

Replace

.responseJSON

with

.responseData

And please name functions and variables with starting lowercase letter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...