如何在iPhone上检测应用程序的首次启动

168

如何检测首次启动

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // if very first launch than perform actionA
  // else perform actionB
}

什么是方法?


我认为https://dev59.com/2FXTa4cB1Zd3GeqP3aPb会对你有所帮助。 - Charan
17个回答

3

针对Xcode 7中Swift 2.0版本。 在AppDelegate.swift文件中:

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool
{
    return true
}


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

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

    if let hasBeenLauncherBefore = defaults.stringForKey("hasAppBeenLaunchedBefore")
    {
        //print(" N-th time app launched ")
        return true
    }
    else
    {
        //print(" First time app launched ")
        defaults.setBool(true, forKey: "hasAppBeenLaunchedBefore")
        return false
    }
}

}

3

已更新至 XCode 12Swift 5

 extension UIApplication {
      func isFirstLaunch() -> Bool {
        if !UserDefaults.standard.bool(forKey: "HasLaunched") {
          UserDefaults.standard.set(true, forKey: "HasLaunched")
          UserDefaults.standard.synchronize()
          return true
      }
      return false
    }
}

然后你可以这样调用它:

UIApplication.isFirstLaunch()

3
你的答案与这个答案https://dev59.com/1mkw5IYBdhLWcg3wVpFi#42509810有何不同? - V.March

3

在Swift中,我建议使用全局常量,这很容易在任何范围之外完成,例如在AppDelegate上面。因此,只要应用程序没有终止,它将设置为正确的值。即使应用程序转到后台或其他状态,它仍将返回相同的值。该值仅在完全重新启动应用程序时更改。

let isFirstLaunch: Bool = {
    if !UserDefaults.standard.bool(forKey: "hasBeenLaunchedBeforeFlag") {
        UserDefaults.standard.set(true, forKey: "hasBeenLaunchedBeforeFlag")
        UserDefaults.standard.synchronize()
        return true
    }
    return false
}()

但是,实际上最好跟踪一下应用程序是否已至少一次被发送到后台。在这种情况下,我更喜欢在UIApplication上使用扩展,并在applicationDidEnterBackground方法中设置标志,如下所示:

extension UIApplication {
    private static let isFirstLaunchKey = "isFirstLaunchKey"
    static var isFirstLaunch: Bool {
        return !UserDefaults.standard.bool(forKey: isFirstLaunchKey)
    }
    static func didEnterBackground() {
        if isFirstLaunch {
            UserDefaults.standard.set(true, forKey: isFirstLaunchKey)
            UserDefaults.standard.synchronize()
        }
    }
}

然后在你的应用委托或场景委托中进行操作。

func sceneDidEnterBackground(_ scene: UIScene) {
        UIApplication.didEnterBackground()
    }

2

swift

struct Pref {
    static let keyFirstRun = "PrefFirstRun"
    static var isFirstRun: Bool {
        get {
            return UserDefaults.standard.bool(forKey: keyFirstRun)
        }
        set {
            UserDefaults.standard.set(newValue, forKey: keyFirstRun)
        }
    }
}

应用程序启动时注册默认值:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let prefs: [String:Any] = [
            Pref.keyFirstRun: true
            ...
        ]

        UserDefaults.standard.register(defaults: prefs)

应用程序终止时清除值:

最初的回答
func applicationWillTerminate(_ application: UIApplication) {
        Pref.isFirstRun = false

Check value:

 if Pref.isFirstRun {
    ... do whatever 

2

Swift 5 iOS 13.

我喜欢由Chris Fremgen编写的快速且简便的方法。因此,我对它进行了更新。

func isFirstTimeOpening() -> Bool {
  let defaults = UserDefaults.standard

  if(defaults.integer(forKey: "hasRun") == 0) {
      defaults.set(1, forKey: "hasRun")
      return true
  }
  return false

}

0

NSUserDefaults + 宏

最好的方法是使用NSUserDefaults并保存一个BOOL变量。 如上所述,以下代码将完美地完成:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:[NSNumber numberWithBool:true] forKey:@"~applicationHasLaunchedBefore"];
[userDefaults synchronize];

您还可以创建以下,以便轻松检查是否为首次启动

#define kApplicationHasLaunchedBefore [[NSUserDefaults standardUserDefaults] objectForKey:@"~applicationHasLaunchedBefore"]

然后像这样使用它,

if (kApplicationHasLaunchedBefore) {
    //App has previously launched
} else {
    //App has not previously launched
}

0
这是一个在 Swift 5.0 中可用的答案。与 @Zaid Pathan 的答案相比,改进之处在于没有隐藏的约定。如果在调用 isFirstAppLaunch() 之前没有确切地调用 setFirstAppLaunch() 一次,将会出现断言错误(仅在调试模式下)。
fileprivate struct _firstAppLaunchStaticData {
    static var alreadyCalled = false
    static var isFirstAppLaunch = true
    static let appAlreadyLaunchedString = "__private__appAlreadyLaunchedOnce"
}

func setFirstAppLaunch() {
    assert(_firstAppLaunchStaticData.alreadyCalled == false, "[Error] You called setFirstAppLaunch more than once")
    _firstAppLaunchStaticData.alreadyCalled = true
    let defaults = UserDefaults.standard

    if defaults.string(forKey: _firstAppLaunchStaticData.appAlreadyLaunchedString) != nil {
        _firstAppLaunchStaticData.isFirstAppLaunch = false
    }
    defaults.set(true, forKey: _firstAppLaunchStaticData.appAlreadyLaunchedString)
}

func isFirstAppLaunch() -> Bool {
    assert(_firstAppLaunchStaticData.alreadyCalled == true, "[Error] Function setFirstAppLaunch wasn't called")
    return _firstAppLaunchStaticData.isFirstAppLaunch
}

然后你只需要在你的应用程序启动时调用函数setFirstAppLaunch(),并在任何时候调用isFirstAppLaunch()来检查您的应用程序是否被调用。


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