如何在swift中按下按钮取消localNotification? [英] how to cancel a localNotification with the press of a button in swift?
问题描述
我只需点击一个按钮即可安排基于 UILocalNotification
的位置。但是当我尝试通过再次单击相同的按钮取消localNotification时,它不会取消通知。
我正在使用 UIApplication.sharedApplication()。cancellocalNotification(localNotification)
取消我的预定位置的本地通知。
我做错了什么?
这里是我的实现
I am scheduling a location based UILocalNotification
with the click of a button . But when i try to cancel the localNotification by clicking the same button again, it doesn't cancel the notification.
I am using UIApplication.sharedApplication().cancelLocalNotification(localNotification)
to cancel my scheduled location based local notification.
What am i doing wrong ?
here is my implementation
@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
块代码,其中我触发本地通知
what should i enter into the else block so that the scheduled notification gets canceled. Cannot clear all notifications.
here is the didEnterRegion
block code where i trigger the local notification
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
localNotification.regionTriggersOnce = true
localNotification.alertBody = "Stack Overflow is great"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
NSLog("Entering region")
}
推荐答案
如果在您的上下文中这是可接受的,您可以尝试删除所有通知。
像这样:
You could try to remove all notifications if this is acceptable in your context. Like this:
for notification in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] {
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
或者如Logan所述:
Or as stated by Logan:
UIApplication.sharedApplication().cancelAllLocalNotifications()
或者如Gerard Grundy对Swift 4所述:
Or as stated by Gerard Grundy for Swift 4:
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
这篇关于如何在swift中按下按钮取消localNotification?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!