2017-10-21 94 views
0

我有一個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 
} 
+0

而不是空的捕獲,打印被捕獲的錯誤;也許你的解碼失敗了。 – Paulw11

+0

打印'sentPost'是什麼? –

+0

你可以發佈'loginUser'示例嗎?你可以發佈樣本數據你期望的數據嗎? –

回答

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() 
+0

它沒有從服務器獲取任何方式,只發送。但是,無論如何謝謝你的結構。 – daniel

+0

您問了另一個問題,因爲這會有用 –

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() 
+0

您複製了我的答案,然後您接受了答案。 –

相關問題