Pages

Saturday 3 January 2015

Detect first time app launch in iOS



Here we can simply  add the if else condition using NSUserDefualts...


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

{
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
        {
            // app already launched
        }
        else
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            // This is the first launch ever
        }
}

    







or else if we want launch count then we can use instead of above follow the below code


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    NSUserDefaults *theDefaults;
    int  launchCount;
    //Set up the properties for the integer and default.
    theDefaults = [NSUserDefaults standardUserDefaults];
    launchCount = [theDefaults integerForKey:@"hasRun"] + 1;
    [theDefaults setInteger:launchCount forKey:@"hasRun"];
    [theDefaults synchronize];
    
    //Log the amount of times the application has been run
    NSLog(@"This application has been run %d amount of times", launchCount);
    
    //Test if application is the first time running
    if(launchCount == 1)
    {
        //Run your first launch code (Bring user to info/setup screen, etc.)
        NSLog(@"This is the first time this application has been run %d ====",launchCount);
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                                  @"Title" message:[NSString stringWithFormat:@"%d",launchCount]  delegate:self
                                                 cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
        [alertView show];
        
    }
              
              //Test if it has been run before
              if(launchCount >= 2)
              {
                  //Run new code if they have opened the app before (Bring user to home screen etc.
                  NSLog(@"This application has been run before==== %d ",launchCount);
                  UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                                            @"Title" message:[NSString stringWithFormat:@"%d",launchCount]  delegate:self
                                                           cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
                  [alertView show];
                }
    
                  
    return YES;
}

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I'm happy to see the considerable subtle element here!. technowalla

    ReplyDelete