我有一个 Node.js 服务器,它在用户登录时发送 JWT(JSON Web 令牌)作为响应。如何在我的 Swift 4、iOS 应用程序中获得响应?
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()
}
它将用户名和密码发送到服务器,但我该怎么做才能得到响应?响应是一个 JWT 令牌,我如何以及在哪里存储它?
这是结构。
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
}