Storing a variable when the app is first installed

我怕爱的太早我们不能终老 提交于 2019-12-01 14:13:18

Hey @Curtis Cowan try with this

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

            let firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunchTime")
            if firstLaunch  {
               println("Not First launch")
            }
            else {
                println("First launch")
                NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey:"FirstLaunchTime")
                 }

            return true
      }

first make your date optional:

var installedDate: NSDate? {
    get {
        return NSUserDefaults().objectForKey("installedDateKey") as? NSDate
    }
    set {
        NSUserDefaults().setObject(newValue, forKey: "installedDateKey")
    }
}

and inside your viewDidLoad method add a conditional to only save its value if it stills nil:

override func viewDidLoad() {
    super.viewDidLoad()
    if installedDate == nil {
        installedDate = NSDate()
        print("First run")
    } else { 
        print("Not first run")
        print(installedDate!)
    }
}

Xcode 8 • Swift 3

var installedDate: Date? {
    get {
        return UserDefaults.standard.object(forKey: "installedDateKey") as? Date
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "installedDateKey")
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!