How to check if your iOS application is running for the first time or not?


Background:~

There are some scenarios where we need to check whether our application is running first time or not.
If it is running first time then and only then execute that code. For Example,

  • Showing help screen
  • Register device for push notification
  • Database creation
  • Server selection and so on…

Implementation:~ 

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

+ (BOOL)isFirstRun ;

@end

Utility.m

#define USER_DEFAULTS_FIRST_RUN @"isFirstRun"
@implementation Utility

+ (BOOL)isFirstRun {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    if ([defaults objectForKey:USER_DEFAULTS_FIRST_RUN]) {
        returnNO;
    }

    [defaults setObject:[NSDate date] forKey:USER_DEFAULTS_FIRST_RUN];
    [defaults synchronize];

    returnYES;
}

How to Use:~

Call “isFirstRun” method from didFinishLaunchingWithOptions from AppDelegate.m class.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions
                   :(NSDictionary *)launchOptions {

    //Check is application is running first time of not

    if ([Utility isFirstRun]) {

        // Application is running first time.
        // Do your stuff here
    }

    returnYES; 

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s