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

时间:2015-08-11 20:14:55

标签: ios iphone swift ios8 uilocalnotification

我只需点击一个按钮即可安排基于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")
}

6 个答案:

答案 0 :(得分:41)

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

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

或者如Logan所述:

UIApplication.sharedApplication().cancelAllLocalNotifications()

或者如Gerard Grundy所说的Swift 4:

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

答案 1 :(得分:3)

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

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

对于Swift 3.0和iOS 10:

UNUserNotificationCenter.current().removeAllDeliveredNotifications()

答案 4 :(得分:0)

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

  

让中心= UNUserNotificationCenter.current()           center.removeDeliveredNotifications(withIdentifiers:[String])           center.removePendingNotificationRequests(withIdentifiers:[String])

答案 5 :(得分:-2)

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

所以你有一个

- IBAction methodName{

//scheduleNotification
//cancelNotification
}

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

Bool didCancel;

- IBAction methodName{

if didCancel == No{
//scheduleNotification
didCancel = YES;
}else if didCancel == YES{
//cancelNotifications
didCancel = NO;
}