How to make HTTP post request with specific body? And how to access token from the server to allow me to login?

后端 未结 1 1899
难免孤独
难免孤独 2021-01-22 10:37

I\'m having a scenario like :

1) I want to create Http POST request and for this I\'m having the data, please see this image:

1条回答
  •  北海茫月
    2021-01-22 11:01

    You are hard coding the username and password in bodyStr update it to

    self.bodyStr = "username=" + actualUsername + "&password=" + actualPassword + "&grant_type=password"
    

    Update the statements inside do with

       do {
    
        let tokenDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! NSDictionary
        print(tokenDictionary)
                                // Get the token
        if let authToken = tokenDictionary["access_token"] as? String{
        self.token = authToken
        UserDefaults.standard.set(accessToken, forKey: "access_token")
        UserDefaults.standard.synchronize()
        DispatchQueue.main.async {
        self.dismiss(animated: true, completion: nil)
        }
        } 
      }
    

    You can implement a function like isUserLoggedIn which will return true if token is saved in userDefaults. You need to check whether the user has logged in in the appDelegate's applicationdidFinishLaunchingWithOptions.Like

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if isUserLoggedIn(){
    //showHomeViewController
    } else{
    //showLoginViewController
    }
    return true
    }
       func isUserLoggedIn() -> Bool{
            if let accessToken = UserDefaults.standard.object(forKey: "access_token") as? String {
                if (accessToken.characters.count)! > 0{
                    return true
                } else {
                    return false
                }
    
            }
            else {
                return false
            }
        }
    

    0 讨论(0)
提交回复
热议问题