3次发布后显示UIAlertview App

时间:2014-10-20 20:13:58

标签: ios objective-c xcode ios7 uialertview

我想要实现的是在用户3次打开应用程序后显示UIAlertview。我在ViewDidAppear的ViewController中使用下面的代码,但每次打开应用程序时都会显示UIAlertview。有人能告诉我这里我做错了什么吗?

int launches = [[NSUserDefaults standardUserDefaults] integerForKey:@"launchCount"];
if (launches > 3) {
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My Alert" 
                                                  message:@"Some message" delegate:nil
                                        cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [alert show];
}
[[NSUserDefaults standardUserDefaults] setInteger:launches+1 forKey:@"launchCount"];

编辑:我也得到一个NSInteger(又名'long')到'int'警告。这可能是它无法正常工作的问题吗?

enter image description here

3 个答案:

答案 0 :(得分:0)

您应该将该代码移到您的应用代理中 -application:didFinishLaunchingWithOptions:

答案 1 :(得分:0)

@ AdamPro13是正确的,你应该移动代码,但可能是你的app委托中的- (void)applicationDidBecomeActive:(UIApplication *)application。每次启动应用都可以多次调用viewDidAppear方法。如果您希望每次安装只显示UIAlertView一次,则可以保存BOOL(如果已显示)或更改测试launches == 4。像

这样的东西
NSInteger launches = [[NSUserDefaults standardUserDefaults] integerForKey:@"launchCount"];
BOOL launchAlertShown = [[NSUserDefaults standardUserDefaults] boolForKey:@"launchAlertShown"];
if (launches > 3 && !launchAlertShown) {
   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My Alert" 
                                              message:@"Some message" delegate:nil
                                    cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [alert show];
  [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"launchAlertShown"];
}
[[NSUserDefaults standardUserDefaults] setInteger:launches+1 forKey:@"launchCount"];

您删除了应用,而不仅仅是使用新版本进行覆盖,以删除[NSUserDefaults standardUserDefaults]的内容。这意味着在您从正在测试的设备或模拟器中删除应用程序之前,测试launches > 3将保持为真。

答案 2 :(得分:0)

知道了!感谢@ AdamPro13

NSInteger launches = [[NSUserDefaults standardUserDefaults] integerForKey:@"launchCount"];
    if (launches % 3 == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My Alert"
                                                        message:@"Some message" delegate:nil
                                              cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }

    [[NSUserDefaults standardUserDefaults] setInteger:launches+1 forKey:@"launchCount"];