我有一个Node.js服务器,当用户登录时,它会发送JWT(JSON Web Token)作为响应。如何在我的Swift 4 iOS应用程序中获得响应?
react-native
它将用户名和密码发送到服务器,但是我从这里做什么来获得响应?响应是JWT令牌,我如何以及在何处存储它?
以下是结构。
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()
}
答案 0 :(得分:0)
根据帖子,我猜你的回答将采用以下格式:
{
"token": "JWT 2424234234234",
"user": {
"id": 1,
"username": "user.username",
"email": "user.email"
}
}
对于上面的JSON,你必须解码如下:
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()
答案 1 :(得分:0)
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()