如何使用SWIFT首次检查IOS应用程序是否正在运行

时间:2015-06-04 04:50:02

标签: ios swift

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
    {
        // app already launched
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        // This is the first launch ever
    }
    return YES;
}

我搜索了这个问题并在 Objective-C 中得到了很多答案。任何人都可以帮助我在 swift 中做到这一点吗?先感谢您。

1 个答案:

答案 0 :(得分:11)

试试这个

if(NSUserDefaults.standardUserDefaults().boolForKey("HasLaunchedOnce") {
  // App already launched

} else {
  // This is the first launch ever
  NSUserDefaults.standardUserDefaults().setBool(true, forKey: "HasLaunchedOnce")
  NSUserDefaults.standardUserDefaults().synchronize()
}

Swift 3版本 - >

if (UserDefaults.standard.bool(forKey: "HasLaunchedOnce")) {
   // App already launched

} else {
   // This is the first launch ever         
   UserDefaults.standard.set(true, forKey: "HasLaunchedOnce")
   UserDefaults.standard.synchronize()
}