Labels

January 8, 2014

Detect First Run of Application

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


#import "Utility.h"

#define USER_DEFAULTS_FIRST_RUN @"isFirstRun"


@implementation Utility


+ (BOOL)isFirstRun {

   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

   if ([defaults objectForKey:USER_DEFAULTS_FIRST_RUN]) {
       return NO;
   }
   
   [defaults setObject:[NSDate date] forKey:USER_DEFAULTS_FIRST_RUN];
   [defaults synchronize];
   
   return YES;

}


How to Use :~


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

AppDelegate.m


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


   //Check is application is running first time of not
   
   if ([[Utility sharedHandler] isFirstRun]) {

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


   }
   return YES;

}