问题
I have a Node.js server that sends JWT(JSON Web Token) as response, when user logs in. How do I get the response in my Swift 4, iOS app?
func handleLogin() {
guard let username = usernameTextField.text, let password =
passwordTextField.text else {
print("Invalid form")
return
}
guard let url = URL(string: "http://localhost:3000/users/authenticate")
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let authUser = Login(username: username, password: password)
do {
let jsonBody = try JSONEncoder().encode(authUser)
request.httpBody = jsonBody
} catch {}
let session = URLSession.shared
let task = session.dataTask(with: request)
task.resume()
}
It sends the username and password to the server, but what do I do from here to get the response? The response is a JWT token, and how and where do i store it?
Here are the structs.
struct Login: Encodable {
let username: String
let password: String
}
struct User: Decodable {
let id: Int
let username: String
let email: String
}
struct Response: Decodable {
let token: String
let user: User
}
回答1:
Based on the post, Iam guessing your response will be in the below format :
{
"token": "JWT 2424234234234",
"user": {
"id": 1,
"username": "user.username",
"email": "user.email"
}
}
For the above JSON you have to decode like below :
struct Response: Codable {
let token: String
let user: User
}
struct User: Codable {
let id: Int
let username: String
let email: String
}
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, _, _) in
guard let data = data else { return }
do {
let sentPost = try JSONDecoder().decode(Response.self, from: data)
print(sentPost.token)
print(sentPost.user.id)
print(sentPost.user.username)
print(sentPost.user.email)
} catch {}
}
task.resume()
回答2:
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, _, _) in
guard let data = data else { return }
do {
let _ = try JSONDecoder().decode(Response.self, from: data)
} catch {
print(String(data: data, encoding: .utf8)!)
}
}
task.resume()
来源:https://stackoverflow.com/questions/46867699/how-do-i-get-the-response-from-node-js-server-in-ios-app