I've followed several tutorials on this, and as far as I can tell what I'm doing should be working. I have the following json response from an api call
{
"Id": "1",
"Name": "Test User",
"Email": "test@email.com",
"ProfileImage": null,
"IsAdmin": true,
"TakesJobs": false,
"IsLocationUser": false,
"IsCompanyAdmin": true,
"LocationUsers": [],
"CompanyUsers": [{
"CompanyName": "Test Company",
"Id": 6,
"CompanyId": 5,
"UserId": "1",
"Admin": true,
"TakesJobs": false,
"UserName": null,
"UserEmail": null,
"AssignedJobs": null
}]
}
Essentially I just want to check if the Id value is blank or not. Here is the code I'm using
The res return type is JSON
ApiConnector.sharedInstance.login(emailText.text!, password: passwordText.text!) { (res) in
if let id = res["Id"] as? String {
if id != "" {
}
else
{
}
}
}
I get a warning that says Cast from 'JSON' to unrelated type 'String' always fails.
What do I need to change to see the value of Id?
This is the code from the ApiConnector class
func login(username: String, password: String, onCompletion: (JSON) -> Void) {
let route = baseURL + "auth?Email=" + username + "&Password=" + password
makeHTTPPostRequest(route, body: ["Email":username, "Password": password], onCompletion: { json, err in
onCompletion(json as JSON)
})
}
答案 0 :(得分:2)
我想你想要这样的东西:
ApiConnector.sharedInstance.login(emailText.text!, password: passwordText.text!) { (res) in
if let id = res["Id"].string {
// Do something.
}
}
答案 1 :(得分:1)
What library are you using for handle json? If swift json you can do something like
res["id"]?.string
If you don't say anything on the type of "res" we can't answer you.