-2

in swift, how can i detect if this is the first time the app is ran ? i want to create a simple game that sets the high score to 0 if the app is new. if i typed this :

 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    

    NSUserDefaults.standardUserDefaults().setObject(0, forKey: "firstrun")
    if ( NSUserDefaults.standardUserDefaults().objectForKey("firstrun")?.integerValue == 0 ){
        
        NSUserDefaults.standardUserDefaults().setObject(0, forKey: "HighScore")
        else {
      
            outputLabel.text = String(NSUserDefaults.standardUserDefaults().objectForKey("HighScore")
      }
}

This "firstrun" will be reseted to 0 after every launch, how can i solve this issue

Machavity
  • 30,841
  • 27
  • 92
  • 100
Wassim Seifeddine
  • 1,002
  • 12
  • 25
  • 1
    http://stackoverflow.com/questions/9964371/how-to-detect-first-time-app-launch-on-an-iphone V. similar question but in obj C. Should be easy to convert – Alec. Dec 15 '14 at 17:17

2 Answers2

3

NSUserDefaults has a registerDefaults: method for this purpose. Use it (in application:didFinishLaunchingWithOptions:).

matt
  • 515,959
  • 87
  • 875
  • 1,141
1

As matt said, registerDefaults was created for this purpose.

However, if you don't want to use registerDefaults, then I'd suggest using integerForKey and setInteger instead of using objectForKey. integerForKey defaults to 0. So if you use it, the HighScore will default to 0 until it is set.

Ron Fessler
  • 2,701
  • 1
  • 17
  • 22