我有一個Node.js服務器在用戶登錄時發送JWT(JSON Web Token)作爲響應。如何在我的Swift 4 iOS應用中獲得響應?如何從iOS應用程序中的Node.js服務器獲取響應?
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
}
而不是空的捕獲,打印被捕獲的錯誤;也許你的解碼失敗了。 – Paulw11
打印'sentPost'是什麼? –
你可以發佈'loginUser'示例嗎?你可以發佈樣本數據你期望的數據嗎? –