0

我有一个 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
}
4

2 回答 2

1

根据帖子,我猜您的回复将采用以下格式:

{
    "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()
于 2017-10-21T21:42:54.110 回答
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()
于 2017-10-22T02:31:58.297 回答