Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a UIAlertView appear only once, at the first start-up of an iPhone app?

I'm using the UIAlertView to make a pop-up happen once the app has started up. It works fine but I only want the pop up to appear on the first start-up of the app. At the moment I've got the UIAlertView in the AppDelegate class, in applicationDidFinishLaunching method. Here is my code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
sleep(4);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Welcome!" message:@"SAMPLE!!!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

I'm new to app development so sorry if this is simple.

like image 277
user309245 Avatar asked Apr 05 '10 14:04

user309245


3 Answers

To determine whether the app is run the first time, you need to have a persistent variable to store this info. NSUserDefaults is the best way to store these simple configuration values.

For example,

-(BOOL)application:(UIApplication *)application … {
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    if (! [defaults boolForKey:@"notFirstRun"]) {
      // display alert...
      [defaults setBool:YES forKey:@"notFirstRun"];
    }
    // rest of initialization ...
}

Here, [defaults boolForKey:@"notFirstRun"] reads a boolean value named notFirstRun from the config. These values are initialized to NO. So if this value is NO, we execute the if branch and display the alert.

After it's done, we use [defaults setBool:YES forKey:@"notFirstRun"] to change this boolean value to YES, so the if branch will never be executed again (assume the user doesn't delete the app).

like image 88
kennytm Avatar answered Nov 02 '22 03:11

kennytm


- (void) displayWelcomeScreen
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *alreadyRun = @"already-run";
    if ([prefs boolForKey:alreadyRun])
        return;
    [prefs setBool:YES forKey:alreadyRun];
    UIAlertView *alert = [[UIAlertView alloc]
        initWithTitle:@"…"
        message:@"…"
        delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];
    [alert release];
}
like image 4
zoul Avatar answered Nov 02 '22 03:11

zoul


Use a NSUserDefault which is initially set to 0 and which you set to 1 after showing the alert for the first time.

//default value is 0
[settings registerDefaults:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:@"HAVE_SHOWN_REMINDER"]];
    BOOL haveShownReminder = [settings boolForKey:@"HAVE_SHOWN_REMINDER"];  
    if (!haveShownReminder)
{
    //show your alert

    //set it to 1
    [[NSUserDefaults standardUserDefaults]  setObject:[NSNumber numberWithInt:1] forKey:@"HAVE_SHOWN_REMINDER"];    
}
like image 3
NeilInglis Avatar answered Nov 02 '22 02:11

NeilInglis