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?
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?
NSUserDefaults + Macro
The best approach is to use
NSUserDefaults
and save aBOOL
variable. As mentioned above, the following code will do just fine:You can also create a macro as below to easily check whether it is the first launch or not
Then use it as such,
I wrote a tiny library for this very purpose. It lets me know whether this is the first launch ever, or just for this version, and any past versions the user has installed. It's available on github as a cocoapod under the Apache 2 license: GBVersionTracking
You just call this in
application:didFinishLaunching:withOptions:
And then to check if this is the first launch just call this anywhere:
And similarly:
In Swift 3, 4 try this:
In Swift 2 try this,
UPDATE:- For OBJ-C I use this,
Ref for OBJ-C: https://stackoverflow.com/a/9964400/3411787
You can implement it with the static method below:
Another idea for Xcode 7 and Swift 2.0 is to use extensions
Now you can write anywhere in your app
I personally prefer an extension of UIApplication like this:
Because the function call is more descriptive:
It's quite simple to do this and requires only six lines of code.
It will be useful to add this code in your application launch preferences or anywhere else you might need to test whether or not its the first time your application has been run.
P.S. Do NOT use bools in preferences Just stick to integers. They default to zero when undefined.
Also, the
[theDefaults synchronize];
line isn't required but I've found that when an app is ran hundreds of times across hundreds of devices, the results aren't always reliable, besides, it's better practice.