ios - 如何通过快速按下按钮取消 localNotification?

标签 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 block 中输入什么,以便取消预定的通知。无法清除所有通知。 这是我触发本地通知的 didEnterRegion block 代码

func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
    localNotification.regionTriggersOnce = true
    localNotification.alertBody = "Stack Overflow is great"
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    NSLog("Entering region")
}

最佳答案

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

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

或者如 Logan 所述:

UIApplication.sharedApplication().cancelAllLocalNotifications()

或者如 Gerard Grundy 为 Swift 4 所述:

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

关于ios - 如何通过快速按下按钮取消 localNotification?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31951142/

相关文章:

iphone - iPhone:“指纹扫描仪”可以作为API使用吗?

ios - 如何将 webview 内容创建为 pdf 文件 ios sdk

swift - 无法打开粒子 SKS 文件

xcode - 为什么我的计时器在 Swift 中不倒计时到 0?

arrays - Swift:编写将从数组中调用随机项目的代码,而不是再次调用该项目

ios - 将图像添加到 Titanium iOS 模块

ios - 无法在 Xcode 中找到设备支持文件

ios - 将 Google Contacts API 集成到我的 Swift 3 应用程序中

iphone - iPhone 中的 SOAP 和 REST 服务

iphone - UIimageView 圆顶角 BezierPath 不起作用?