2013-12-08 16 views
0

我正在製作一個計時器應用程序。用戶從那裏設置時間和應用程序倒數。我添加了一個UILocalNotification,使其彈出,即使你是不是在應用程序告訴你的計時器已經完成:暫停UILocalNotification

在我的視圖控制器:

- (void)setupLocalNotifications { 
[[UIApplication sharedApplication] cancelAllLocalNotifications]; 

UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 

totalSeconds = (setHour * 60 * 60) + (setMinute * 60) + (setSecond); 

NSDate *now = [NSDate date]; 
NSDate *dateToFire = [now dateByAddingTimeInterval:totalSeconds]; 

localNotification.fireDate = dateToFire; 
localNotification.alertBody = @"Timer Done"; 
localNotification.soundName = UILocalNotificationDefaultSoundName; 
localNotification.applicationIconBadgeNumber = 1; // increment 

NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Object 1", @"Key 1", @"Object 2", @"Key 2", nil]; 
localNotification.userInfo = infoDict; 

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
} 

IN MY的appdelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
// Override point for customization after application launch.; 

ScrollViewController *sv = [[ScrollViewController alloc] init]; 

UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; 

if (notification) { 
    [self showAlarm:notification.alertBody]; 
    NSLog(@"AppDelegate didFinishLaunchingWithOptions"); 
    application.applicationIconBadgeNumber = 0; 
} 

self.window.rootViewController = sv; // Make tab bar controller the root view controller 
[self.window makeKeyAndVisible]; 
return YES; 
} 

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { 
[self showAlarm:notification.alertBody]; 
application.applicationIconBadgeNumber = 0; 
NSLog(@"AppDelegate didReceiveLocalNotification %@", notification.userInfo); 
} 

- (void)showAlarm:(NSString *)text { 
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Timer" 
                message:text 
                delegate:self 
              cancelButtonTitle:@"Stop Timer" 
              otherButtonTitles:nil]; 
[alertView show]; 
} 

會發生什麼事是,我設置了一個UILocalNotification在用戶定義的秒數過去後關閉。但是,我的應用程序允許您暫停計時器。暫停時,UILocalNotification將繼續,並在秒數過後關閉。有沒有辦法暫停本地通知?

回答

5

本地通知無法暫停。如果定時器在您的應用程序中暫停, 您應該取消通知,並且如果定時器 恢復,則創建/調度新定時器。

+0

好的,謝謝。這是通過將localNotification設置爲零來完成的嗎? – user2397282

+0

@ user2397282:否。如果您只有一個通知,那麼最簡單的方法是調用'[[UIApplication sharedApplication] cancelAllLocalNotifications]'。 –

+0

或者保留一個指向通知對象的指針並使用cancelLocalNotification,如果有多個並且你只想取消它。 –