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

我怎样才能检测到第一次发射的

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

方法?

96594 次浏览
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
return YES;
}

您需要在启动时保存某些内容,然后检查它是否存在。如果没有,这是第一次。“ Something”可以是一个文件、一个数据库条目、一个用户默认设置... ..。

存储一个 bool 密钥在 NSUserDefault 第一次它将是否,你将改变它为是,并保持这样,直到应用程序删除或重新安装它将再次像第一次。

我写了一个很小的图书馆就是为了这个目的。它让我知道这是否是有史以来的第一次启动,或者只是为了这个版本,以及用户安装的任何过去的版本。它可以在 github 上作为 cocoapod 获得 Apache2许可证: GBVersionTrace

你只要用 application:didFinishLaunching:withOptions:打电话

[GBVersionTracking track];

然后检查这是否是第一次发射,只需要在任何地方调用这个:

[GBVersionTracking isFirstLaunchEver];

同样地:

[GBVersionTracking isFirstLaunchForVersion];


[GBVersionTracking currentVersion];
[GBVersionTracking previousVersion];
[GBVersionTracking versionHistory];

你可以用下面的静态方法来实现它:

+ (BOOL)isFirstTime{
static BOOL flag=NO;
static BOOL result;


if(!flag){
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"hasLaunchedOnce"]){
result=NO;
}else{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
result=YES;
}


flag=YES;
}
return result;
}

这样做非常简单,只需要6行代码。

将这段代码添加到应用程序启动首选项中,或者添加到您可能需要测试应用程序是否首次运行的其他任何地方,将非常有用。

//These next six lines of code are the only ones required! The rest is just running      code when it's the first time.
//Declare an integer and a default.
NSUserDefaults *theDefaults;
int  launchCount;
//Set up the properties for the integer and default.
theDefaults = [NSUserDefaults standardUserDefaults];
launchCount = [theDefaults integerForKey:@"hasRun"] + 1;
[theDefaults setInteger:launchCount forKey:@"hasRun"];
[theDefaults synchronize];


//Log the amount of times the application has been run
NSLog(@"This application has been run %d amount of times", launchCount);


//Test if application is the first time running
if(launchCount == 1) {
//Run your first launch code (Bring user to info/setup screen, etc.)
NSLog(@"This is the first time this application has been run";
}


//Test if it has been run before
if(launchCount >= 2) {
//Run new code if they have opened the app before (Bring user to home screen etc.
NSLog(@"This application has been run before);
}

只要保持整数,如果没有定义,它们就默认为零。

此外,[theDefaults synchronize];行不是必需的,但我发现,当一个应用程序在数百个设备上运行数百次时,结果并不总是可靠的,此外,这是更好的做法。

功能简单快捷

- (BOOL) isFirstTimeOpening {
NSUserDefaults *theDefaults = [NSUserDefaults standardUserDefaults];
if([theDefaults integerForKey:@"hasRun"] == 0) {
[theDefaults setInteger:1 forKey:@"hasRun"];
[theDefaults synchronize];
return true;
}
return false;
}

斯威夫特三,四试试这个:

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

if defaults.bool(forKey: "isAppAlreadyLaunchedOnce"){
print("App already launched : \(isAppAlreadyLaunchedOnce)")
return true
}else{
defaults.set(true, forKey: "isAppAlreadyLaunchedOnce")
print("App launched first time")
return false
}
}

Swift 2试试这个,

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

if defaults.boolForKey("isAppAlreadyLaunchedOnce"){
print("App already launched : \(isAppAlreadyLaunchedOnce)")
return true
}else{
defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
print("App launched first time")
return false
}
}

更新:- 对于 OBJ-C,

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

OBJ-C 的裁判: https://stackoverflow.com/a/9964400/3411787

对于 Xcode 7中的 Swift 2.0。 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
}
}


}

Xcode 7和 Swift 2.0的另一个想法是使用扩展

extension NSUserDefaults {
func isFirstLaunch() -> Bool {
if !NSUserDefaults.standardUserDefaults().boolForKey("HasAtLeastLaunchedOnce") {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "HasAtLeastLaunchedOnce")
NSUserDefaults.standardUserDefaults().synchronize()
return true
}
return false
}
}

现在你可以在你的应用程序的任何地方写

if NSUserDefaults.standardUserDefaults().isFirstLaunch() {
// do something on first launch
}

我个人更喜欢这样的 UIApplication 扩展:

extension UIApplication {
class func isFirstLaunch() -> Bool {
if !NSUserDefaults.standardUserDefaults().boolForKey("HasAtLeastLaunchedOnce") {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "HasAtLeastLaunchedOnce")
NSUserDefaults.standardUserDefaults().synchronize()
return true
}
return false
}
}

因为函数调用更具描述性:

if UIApplication.isFirstLaunch() {
// do something on first launch
}

NSUserDefault + 宏

最好的方法是使用 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
}

用于 Swift 3.0-Swift 5

加长

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

然后在你的代码中

UIApplication.isFirstLaunch()

以下是 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()

迅速

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

检查值:

 if Pref.isFirstRun {
... do whatever

在迅速,我建议使用一个全局常量,可以很容易地做任何范围之外,如上面的应用程序委托。因此,只要应用程序没有终止,它就会被设置为正确的值。如果应用程序进入后台,它仍然会返回相同的值。只有当应用程序完全重新启动时,价值才会改变。

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

但老实说,最好是追踪应用程序已被发送到后台至少一次的事实。在这种情况下,我倾向于在 UIApplication 上使用一个扩展,并在 applicationDidEnterBack 方法中设置标志,以便:

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

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


}

更新为 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()