Search code examples
swiftnsuserdefaultskeychain

How to save object into UserDefaults or keychain - Swift 3


I'm building a Shopify app, but first and foremost this is NOT a Shopify SDK question, it's regarding saving a customer token into userDefaults or Keychain. I've tried but most Keychain libraries I've tried only work with strings and I need to save the token as a whole which looks like this:

BUYCustomerToken(customerID: NSNumber!, accessToken: String!, expiry: Date!)

The shared client of the app to access the token looks like this:

BUYClient.sharedClient.customerToken

During sign up, user gets created successfully with token. Once I exit and go back into the app the

BUYClient.sharedClient.customerToken = ""

So my question is, how do I save this object into defaults or Keychain to recall later when entering app. I can't just save part of the token, like the accessToken which is just a String, I need the whole thing. Thanks in advance!


Solution

  • You can save more than String types in UserDefaults, you have to store your token in multiple keys.

    https://developer.apple.com/reference/foundation/userdefaults

    The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list—that is, an instance of (or for collections, a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.

    if you want to store the expiry date

    let expiry = UserDefaults.standard.object(forKey: "expiry") as? Date
    UserDefaults.standard.set(Date(), forKey: "expiry")
    

    The CustomerID

    let customerID = UserDefaults.standard.object(forKey: "customerID") as? NSNumber
    UserDefaults.standard.set(1234, forKey: "customerID")
    

    And for the token the same.

    NSUserDefaults.standardUserDefaults().setObject("YourAccessToken", forKey: "accessToken")
    
    let accessToken = NSUserDefaults.standardUserDefaults().stringForKey("accessToken")
    

    With this way, you just have to get them one by one, but you have all of them stored. I hope it helps you!