How to detect first time app launch on an iPhone

2018-12-31 23:46发布

How can I detect the very first time launch of

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

method?

标签: iphone ios
12条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 23:49

for swift 3.0

add extension

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

then in your code

UIApplication.isFirstLaunch()
查看更多
心情的温度
3楼-- · 2018-12-31 23:54

You need to save something when you launch and then check to see if it exists. If not, it's the first time. "Something" can be a file, a database entry, a setting in user defaults....

查看更多
不再属于我。
4楼-- · 2018-12-31 23:55

For Swift 2.0 in Xcode 7. In the AppDelegate.swift file:

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

}
查看更多
看风景的人
5楼-- · 2018-12-31 23:55

Quick and easy function

- (BOOL) isFirstTimeOpening {
    NSUserDefaults *theDefaults = [NSUserDefaults standardUserDefaults];
    if([theDefaults integerForKey:@"hasRun"] == 0) {
        [theDefaults setInteger:1 forKey:@"hasRun"];
        [theDefaults synchronize];
        return true;
    }
    return false;
}
查看更多
回忆,回不去的记忆
6楼-- · 2019-01-01 00:00
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    return YES;
}
查看更多
深知你不懂我心
7楼-- · 2019-01-01 00:00

store a bool key in NSUserDefaults first time it will be no you will change it to yes and keep it like that until the app delete or reinstall it will be again tha first time.

查看更多
登录 后发表回答