How to store tokens in iOS?

Viewed 2835

I'm doing a small project to prepare for server linking, but I'm trying to save the token in Userdefault! I don't know how to code.

var headers: [String: String]? {
    switch self {
    case .signIn:
        return nil
        
    case .renewalToken:
        guard let token = UserDefaults.standard.set("userID", forKey: "signIn") else{
        return ["Authorization": "Bearer " + token]
        }
    default:
        guard let token = UserDefaults.standard.set(<#T##value: Any?##Any?#>, forKey: <#T##String#>)
        return ["Authorization": "Bearer " + token]
    }
}

This code can be obtained by putting it in the code below using the header, but I don't know what to do with the token

   func get(_ api: TargetType) -> DataRequest{
    return AF.request(baseURI + api.path, method: .get, parameters: api.parameters, encoding: JSONEncoding.prettyPrinted, headers: api.headers, interceptor: nil)
}
1 Answers

First of all you should not store sensitive information into the user defaults. I would recommend you to use keychain. It's highly secure.

There are several Libraries which give simple and easy to use interfaces of keychain

SwiftyKeychainWrapper is one of them:

https://github.com/jrendel/SwiftKeychainWrapper

Update -

You need to access user default values using following code:

let token = UserDefaults.standard.string(forKey: “keyName”) ?? “”

Note: if token doesn't exist then you can just navigate user to the Login screen for authentication and regeneration of token.

Related