2014-10-20 51 views
0

我試圖實現的是當用戶在3次後打開應用程序時顯示UIAlertview。我在ViewDidAppear的ViewController中使用下面的代碼,但是每次打開應用程序時都會顯示UIAlertview。有人能告訴我我在這裏做錯了嗎?3啓動後顯示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(又名'長')'int'警告。這可能是爲什麼它不起作用的問題嗎?

enter image description here

+1

要修復警告,請將'int'更改爲'NSInteger'。 – AdamPro13 2014-10-20 20:17:19

+0

[顯示uialertview 3次後打開應用程序?]的可能重複?(http://stackoverflow.com/questions/26471780/show-uialertview-after-opening-an-app-after-3-times)什麼目的是有兩次問相同的問題? – Popeye 2014-10-30 13:16:57

回答

0

你應該代碼轉移到應用程序委託中 -application:didFinishLaunchingWithOptions:

+0

不會,每次打開應用程序時,仍然會顯示警告和警報視圖彈出窗口。 – Jan 2014-10-20 20:21:44

+0

檢查首次啓動時啓動的返回值。此外,您是否希望在第三次啓動後或第三次啓動後每次啓動應用程序時都會顯示警報? – AdamPro13 2014-10-20 20:24:52

+0

如何檢查返回的值?是的,我希望每次在第3次發佈後啓動應用程序時都會展示它。 – Jan 2014-10-20 20:27:51

0

@ AdamPro13是正確的,你應該在你的應用程序代理移動代碼,但可能是- (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將保持爲真,直到您從您正在測試的設備或模擬器刪除應用程序。,

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"]; 
相關問題