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

sum*_*esh 17 iphone ios uilocalnotification swift ios8

我正在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 }
Run Code Online (Sandbox Code Playgroud)

我该怎么进入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")
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*cki 46

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

for notification in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] { 
  UIApplication.sharedApplication().cancelLocalNotification(notification)
}
Run Code Online (Sandbox Code Playgroud)

或者如Logan所述:

UIApplication.sharedApplication().cancelAllLocalNotifications()
Run Code Online (Sandbox Code Playgroud)

或者如Gerard Grundy对Swift 4所述:

UNUserNotificationCenter.current().removeAllPendingNotificat??ionRequests()
Run Code Online (Sandbox Code Playgroud)

  • 如果你打算取消所有这些,可能只是使用:`UIApplication.sharedApplication().cancelAllLocalNotifications()` (12认同)
  • **Swift4.1**更新Logans和→UIApplication.shared.cancelAllLocalNotifications() (2认同)

gle*_*ant 8

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

let center = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: [String])
center.removePendingNotificationRequests(withIdentifiers: [String])
Run Code Online (Sandbox Code Playgroud)