how to determine in applicationDidBecomeActive whether it is the initial iPhone app launch?

北城以北 提交于 2019-12-03 17:39:11

问题


how to determine in how to determine in UIApplicationDidBecomeActiveNotification whether it is the initial app launch?whether it is the initial app launch?

that is the initial start up of the application, as opposed to subsequent DidBecomeActive's due to the application being put in background and then to foreground (e.g. user goes to calendar then back to your app)


回答1:


In your applicationDidFinishLaunching:withOptions: put this:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"alreadyLaunched"];
[[NSUserDefaults standardUserDefaults] synchronize];

Then, in didBecomeActive:

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"alreadyLaunched"]) {
    // is NOT initial launch...
} else {
    // is initial launch...
}



回答2:


FWIW, the accepted answer tells you if the app has ever been launched before, not if the app is resuming from the background vs launching. Once the alreadyLaunched key has been set in preferences it will return YES when the app is launched in the future (vs resumed from background).

To detect if the app has resumed from the background you don't need to add anything to preferences. Rather, do the following in your app delegate implementation.

// myAppDelegate.m
//

@interface MyAppDelegate()
@property (nonatomic) BOOL activatedFromBackground;
@end

@implementation MyAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.activatedFromBackground = NO;

    // your code
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    self.activatedFromBackground = YES;

    // your code
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if (self.activatedFromBackground) {
        // whatever you want here
    }
}

@end



回答3:


I used to use the method mentioned by @XJones. Then I realized it has a potential issue: if "the initial app launch" means to check in applicationDidBecomeActive whether it was called the first time since the app was launched! Because when app was relaunching the app (either through springboard, app switching or URL) all the above 3 delegate method will be called! So the safest way is to reset self.activatedFromBackground in applicationDidBecomeActive.



来源:https://stackoverflow.com/questions/7733730/how-to-determine-in-applicationdidbecomeactive-whether-it-is-the-initial-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!