Detect first launch of iOS app [duplicate]

2020-01-24 10:43发布

I am trying to find a way in Swift to detect the first launch.

标签: ios swift
9条回答
▲ chillily
2楼-- · 2020-01-24 11:34

In case of Swift In applicationdidFinishLaunchingWithOptions in AppDelegate Add:

 if NSUserDefaults.standardUserDefaults().boolForKey("isFirstLaunch") {

        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isFirstLaunch")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

And Use this wherever you want to.

let isFirstLaunch = NSUserDefaults.standardUserDefaults().valueForKey("isFirstLaunch") as? Bool
    if isFirstLaunch {
    //It's the initial launch of application.
    }
    else {
    // not initial launch
    }
查看更多
▲ chillily
3楼-- · 2020-01-24 11:37
let applicationLaunchedOnce: Bool = {
        let launchedOnce = NSUserDefaults.standardUserDefaults().boolForKey(UserDefaultsService.ApplicationLaunchedOnce)
        if launchedOnce {
            return launchedOnce
        } else {
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: UserDefaultsService.ApplicationLaunchedOnce)
            NSUserDefaults.standardUserDefaults().synchronize()
            return false
        }
    }()
查看更多
叼着烟拽天下
4楼-- · 2020-01-24 11:38

Typically you would write a value to NSUserDefaults to indicate that an app has launched before.

let launchedBefore = NSUserDefaults.standardUserDefaults().boolForKey("launchedBefore")
if launchedBefore  {
    print("Not first launch.")
}
else {
    print("First launch, setting NSUserDefault.")
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "launchedBefore")
}

UPDATE - Swift 3

let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
if launchedBefore  {
    print("Not first launch.")
} else {
    print("First launch, setting UserDefault.")
    UserDefaults.standard.set(true, forKey: "launchedBefore")
}
查看更多
登录 后发表回答