首次安装应用时存储变量

时间:2016-01-18 02:55:09

标签: ios swift nsuserdefaults

尝试在首次安装应用时存储变量DateInstalled,但每次应用加载此变量时都会被新日期覆盖。

我是Xcode的新手,所以答案很明显。我发现下面的代码将变量存储在用户默认值中,但每次它似乎跳到else语句。

var DateInstalled: NSDate {
    get {
        if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("DateInstalled") as? NSDate {     
            return returnValue
        } else {
            NSLog("Saving new Date")
            return NSDate()          // Default value
        }
    }
    set {
        NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "DateInstalled")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}

2 个答案:

答案 0 :(得分:1)

嘿@Curtis Cowan试试这个

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
      }

答案 1 :(得分:0)

首先让你的日期可选:

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

并在viewDidLoad方法中添加一个条件,只保存其值仍为零:

var installedDate: Date? {
    get {
        return UserDefaults.standard.object(forKey: "installedDateKey") as? Date
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "installedDateKey")
    }
}

Xcode 8•Swift 3

installer_type