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

青春壹個敷衍的年華 提交于 2019-12-04 07:50:36

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

- (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];
}

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"];    
}

3 simple lines

-(BOOL)application:(UIApplication *)applicationBlahBlah {
    if(![[[NSUserDefaults standardUserDefaults] objectForKey:@"NOT_FIRST_TIME"] boolValue])
    {
        [[[[UIAlertView alloc] initWithTitle:nil message:@"message" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease] show];
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"NOT_FIRST_TIME"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

As above solution should work in most cases, i would like to keep you aware on below as well at this point in time.

Apple document says: The NSUserDefaults class does not currently support per-host preferences. To do this, you must use the CFPreferences API. Ref NSUserDefaults

And a discussion on this here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!