Search code examples
iosswifttokenaccess-token

Swift 3.0 token expire how will be call the token automatically?


Once the token is received, when the token is over, then how can I call the token automatically after the login? on same page

 Alamofire.request(urlString, method: .post, parameters: newPost, encoding: JSONEncoding.default)
        .responseJSON { response in

            if let json = response.result.value as? [String : Any]{
                print("JSON: \(json)")
                if UserDefaults.standard.bool(forKey: "logged_in") {

                    Token = json["Token"]! as! String

                    UserDefaults.standard.set(Token, forKey: "Token")
                    UserDefaults.standard.synchronize()

                }

            } else {
                print("Did not receive json")
            }

            //expectation.fulfill()
    }

Solution

  • Scenario 1 : You need to tell to backend developer who made your webservice, that he need to check if TOKEN is valid or not. if token is expired he need to give message code or message that "Token has been expired" and you can check in Response if message code is for expired than you need to navigate your Login screen. This is best practice.

    Scenario 2 : If you dont want to Logout from app, and keep app going with new token automatically refresh, tell webservice developer that whenever token will be expired he will return new Token in response field as "Authorization" And from your code side, you need to check in each request whether Authorization contains new token.. if it contains that means you need to replace old token with New one in userdefault.

    Below is my code in Swift3 :

    func requestApiCall(_ urlString: String, paramData: NSObject, completionHandler: @escaping (NSDictionary?, NSError?) -> ()) {
        let token =   UserDefaults.standard.object(forKey: “token” as String)
        var headersVal = [
            "Authorization": "Bearer "+(token as String),
        ]      
     Alamofire.request(urlString, method: .post, parameters: paramData as? [String : AnyObject],encoding: JSONEncoding.default, headers: headersVal)
    
            .responseJSON { response in
                if let authorization = response.response?.allHeaderFields["Authorization"] as? String {
    
                    var newToken : String = authorization
                    UserDefaults.standard.set(newToken, forKey: "token")
                    UserDefaults.standard.synchronize()
                }
    
                switch response.result {
    
                case .success(let value):
    
                  if let res = response.result.value {
                         let response = res as! NSDictionary
                         let message = response.object(forKey: "message")!
                         print(message)
                    if message as! String ==  "Token has been expired" 
                    {
                        self.showLoginScreen()
                    }
                  }
                completionHandler(value as? NSDictionary, nil)
    
                case .failure(let error):
                    if error._code == -1001 {
                        print("timeout")
                    }
                    completionHandler(nil, nil)
                }
          }
    }