views:

357

answers:

3

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 happen on the first start-up of the app. At the moment I've got the UIAlertView in the AppDelegate class, after the application didFinishLaunching. Here is my code at the moment.

- (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. Thanks in advance! :)

+2  A: 

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"];    
}
NeilInglis
Isn’t the `registerDefaults:` extra?
zoul
+1  A: 
- (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];
}
zoul
+3  A: 

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).

KennyTM