如何在iOS中检测应用程序的首次启动?

16

我希望在用户首次打开我的应用程序时显示欢迎屏幕。有没有一种方法可以在Swift中检查应用程序的首次启动?

9个回答

40

Swift 4及以上版本

您可以在任何地方使用此代码来验证用户是否首次查看此视图。

func isAppAlreadyLaunchedOnce() -> Bool {
    let defaults = UserDefaults.standard
    if let _ = defaults.string(forKey: "isAppAlreadyLaunchedOnce") {
        print("App already launched")
        return true
    } else {
        defaults.set(true, forKey: "isAppAlreadyLaunchedOnce")
        print("App launched first time")
        return false
    }
}

注意:在用户重新安装应用并首次启动后,该方法将返回false


如果您在应用程序的多个位置请求它,则对于第二个和随后的请求,它将返回TRUE,尽管实际上可能是第一次运行。最好使用启动计数器。 - VyacheslavBakinkskiy
启动计数器方法是什么? - Rolando
我猜 @VyacheslavBakinkskiy 的意思是使用 Int 而不是保存 Boolean,这样你就知道应用程序实际启动了多少次。 - Jonas Deichelmann

16

尝试以下方法,适用于Swift 2及以下版本

func isAppAlreadyLaunchedOnce()->Bool{
    let defaults = NSUserDefaults.standardUserDefaults()

    if let isAppAlreadyLaunchedOnce = defaults.stringForKey("isAppAlreadyLaunchedOnce"){
        println("App already launched")
        return true
    }else{
        defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
        println("App launched first time")
        return false
    }
}

这个函数的原始版本可能会在应该返回false时返回true,反之亦然;我不确定;在XCode 9 Beta(用于Swift 4)中使用它,编辑器提供了更新的名称和逻辑建议,导致出现这种情况。 - Alex Hall
感谢 @AlexHall 指出问题,我会更新函数以确保它能够正常工作。 - Mohammad Zaid Pathan

9

由于应用程序的NSUserDefaults在卸载应用程序时被清除,因此您可以尝试在应用程序启动时测试特定值的存在。

如果该值存在,则该应用程序已经安装。如果不存在,则这是第一次启动该应用程序,并且您需要设置该值。


3

SWIFT :

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")
}

目标 - C:

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isAppAlreadyLaunchedOnce"])
{
    return true;
}
else
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isAppAlreadyLaunchedOnce"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    return false;
}

1
不要使用 -[NSUserDefaults synchronize]。根据苹果文档的说明,"这个方法是不必要的,不应该被使用"。 - Ashley Mills

3

Swift 5

let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore") 
   
if launchedBefore {
// Code if has launched before
} else {
UserDefaults.standard.set(true, forKey: "launchedBefore")
// Code if not has launched before
}

2
我经常发现由于苹果的数据保护政策中的一些漏洞userDefault无法访问。因此,我改变了我的策略,使用以下方法检测首次启动。
if ( fileExists( dummyFilePath ) == NO ) {
    createFileAt( dummyFilePath )
    // This is first launch
}

1

Jonas Deichelmann的回答进行了轻微的语义修改,澄清了一些事情:

  • The function name "establishUserDefaultsHaveBeenVerifed" provides a suggestion that the userDefaults aren't just being checked, but may also be written to.
  • The key previously suggested, "isAppAlreadyLaunchedOnce", describes something the function itself has no control over; that key will only correctly describe the launch state if the function is called at the right time by other code, which again, the function itself can't control. Using the key "userDefaultsHaveBeenVerified" instead makes clear that the only thing the function verifies is that it itself has been run before.
  • The print statements make clear that this function is only verifying if it has been run since last installation, not whether or not it has ever been run on this device.

    func establishUserDefaultsHaveBeenVerifed()->Bool{
         let defaults = UserDefaults.standard
         if let _ = defaults.string(forKey: "userDefaultsHaveBeenVerified"){
             print("user defaults were already verified")
             return true
          }else{
             defaults.set(true, forKey: "userDefaultsHaveBeenVerified")
             print("verified user defaults for first time since app was installed")
             return false
          }
     }
    

1

Objective-C版本的Jon Shier's answer

BOOL isAppLaunched = [[NSUserDefaults standardUserDefaults] boolForKey:@"launchedBefore"];
if (isAppLaunched) {
    NSLog(@"Not first launch.");
}
else {
    NSLog(@"First launch, setting NSUserDefault.");
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"launchedBefore"];
}

0

当你需要在第一次会话时执行某些操作(例如,显示应用程序评分):

@UserDefault(key: UDKey.isFirstSession, defaultValue: true)
static var isFirstSession: Bool

func applicationWillTerminate(_ application: UIApplication) {
    // When app is terminated, next sessions are not first anymore
    UserDefaults.isFirstSession = false
}

@UserDefault是什么:

@propertyWrapper
struct UserDefault<Value> {
    let key: String
    let defaultValue: Value
    var container: UserDefaults = .standard

    var wrappedValue: Value {
        get {
            return container.object(forKey: key) as? Value ?? defaultValue
        }
        set {
            container.set(newValue, forKey: key)
        }
    }
}

UDKey 是什么:

enum UDKey {
    static let isFirstSession = "isFirstSession"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接