Invictus Cody
Invictus Cody

Reputation: 517

Checking if an NSUserDefaults key exists or not crashes the app

The following code is in my AppDelegate didFinishLaunchingWithOptions launchOptions: method. When I try to run the app, it crashes.

var accessToken = ""
if let key = NSUserDefaults.standardUserDefaults().objectForKey("accesstoken"){
         accessToken = key as! String
        }

The only crash log I get from Xcode is:

enter image description here

I also have tried :

if  NSUserDefaults.standardUserDefaults().objectForKey("accesstoken") != nil {
}

Can anyone help me to solve the issue ?

Upvotes: 1

Views: 1500

Answers (1)

0xT0mT0m
0xT0mT0m

Reputation: 656

Try optional casting

var accessToken:String? = nil
if let key = NSUserDefaults.standardUserDefaults().objectForKey("accesstoken") as? String {
    accessToken = key
}

Upvotes: 3

Related Questions