Как отменить localNotification нажатием кнопки в swift?
Я планирую размещение на основе UILocalNotification
одним нажатием кнопки. Но когда я пытаюсь отменить localNotification, снова нажав ту же кнопку, он не отменяет уведомление.
Я использую UIApplication.sharedApplication().cancelLocalNotification(localNotification)
для отмены локального уведомления на основе запланированного местоположения.
Что я делаю не так?
вот моя реализация
@IBAction func setNotification(sender: UIButton!) {
if sender.tag == 999 {
sender.setImage(UIImage(named: "NotificationFilled")!, forState: .Normal)
sender.tag = 0
regionMonitor() //function where notification get scheduled
} else {
sender.setImage(UIImage(named: "Notification")!, forState: .Normal)
sender.tag = 999 }
что мне нужно ввести в блок else, чтобы уведомление о расписании было отменено. Невозможно очистить все уведомления.
вот блок didEnterRegion
, где я запускаю локальное уведомление
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
localNotification.regionTriggersOnce = true
localNotification.alertBody = "Qaru is great"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
NSLog("Entering region")
}
Ответы
Ответ 1
Вы можете попытаться удалить все уведомления, если это приемлемо в вашем контексте.
Вот так:
for notification in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] {
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
Или как указано Logan:
UIApplication.sharedApplication().cancelAllLocalNotifications()
Или, как указано Джерардом Гранди для Swift 4:
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
Ответ 2
Решение для iOS 10+ Swift 3.1
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications() // To remove all delivered notifications
center.removeAllPendingNotificationRequests()
Ответ 3
Вы можете сохранить уникальное значение для ключа в локальном уведомлении пользователя и отменить его, получив локальное значение, используя этот ключ Value.
Попробуйте это (для Objective C):
NSArray *notifArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (int i=0; i<[notifArray count]; i++)
{
UILocalNotification* notif = [notifArray objectAtIndex:i];
NSDictionary *userInfoDict = notif.userInfo;
NSString *uniqueKeyVal=[NSString stringWithFormat:@"%@",[userInfoDict valueForKey:@"UniqueKey"]];
if ([uniqueKeyVal isEqualToString:keyValToDelete])
{
[[UIApplication sharedApplication] cancelLocalNotification:notif];
break;
}
}
Ответ 4
Для Swift 3.0 и iOS 10:
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
Ответ 5
Трудно сказать, не видя реализации кода.
поэтому у вас есть
- IBAction methodName{
//scheduleNotification
//cancelNotification
}
Это верно? Если так, добавьте bool, поэтому
Bool didCancel;
- IBAction methodName{
if didCancel == No{
//scheduleNotification
didCancel = YES;
}else if didCancel == YES{
//cancelNotifications
didCancel = NO;
}