如何在swift中按下按钮取消localNotification?

问题描述 投票:14回答:6

我只需点击一个按钮即可安排基于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 = "Stack Overflow is great"
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    NSLog("Entering region")
}
ios iphone swift ios8 uilocalnotification
6个回答
43
投票

如果在您的上下文中这是可接受的,您可以尝试删除所有通知。像这样:

for notification in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] { 
  UIApplication.sharedApplication().cancelLocalNotification(notification)
}

或者如Logan所述:

UIApplication.sharedApplication().cancelAllLocalNotifications()

或者如Gerard Grundy对Swift 4所述:

UNUserNotificationCenter.current().removeAllPendingNotificat‌​ionRequests()

4
投票

适用于iOS 10+ Swift 3.1的解决方案

let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications() // To remove all delivered notifications
center.removeAllPendingNotificationRequests()

1
投票

您可以在本地通知的userinfo中为密钥保存唯一值,并通过使用该密钥的值获取本地通知来取消它。试试这个(对于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;
    }
}

1
投票

对于Swift 3.0和iOS 10:

UNUserNotificationCenter.current().removeAllDeliveredNotifications()

0
投票

您可以使用其标识符取消所需的通知:

let center = UNUserNotificationCenter.current()center.removeDeliveredNotifications(withIdentifiers:[String])center.removePendingNotificationRequests(withIdentifiers:[String])


-3
投票

很难说没有看到代码的实现。

所以你有一个

- IBAction methodName{

//scheduleNotification
//cancelNotification
}

那是对的吗?如果是这样的话加一个bool

Bool didCancel;

- IBAction methodName{

if didCancel == No{
//scheduleNotification
didCancel = YES;
}else if didCancel == YES{
//cancelNotifications
didCancel = NO;
}
© www.soinside.com 2019 - 2024. All rights reserved.