如何通过快速按下button取消LocalNotification?
我正在通过单击button来安排一个基于位置的UILocalNotification
。 但是当我尝试通过再次单击相同的button取消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") }
如果在您的上下文中可以接受,则可以尝试删除所有通知。 喜欢这个:
for notification in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] { UIApplication.sharedApplication().cancelLocalNotification(notification) }
或者如Logan所述:
UIApplication.sharedApplication().cancelAllLocalNotifications()
或者像Gerard Grundy所说的Swift 4:
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
您可以在本地通知的用户信息中保存唯一的密钥值,并通过使用该密钥的值获取localnotification来取消它。 试试这个(对于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; } }
iOS 10 + Swift 3.1的解决scheme
let center = UNUserNotificationCenter.current() center.removeAllDeliveredNotifications() // To remove all delivered notifications center.removeAllPendingNotificationRequests()
对于Swift 3.0和iOS 10:
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
很难说没有看到代码的实施。
所以你有一个
- IBAction methodName{ //scheduleNotification //cancelNotification }
这是对的吗? 如果是这样添加一个布尔
Bool didCancel; - IBAction methodName{ if didCancel == No{ //scheduleNotification didCancel = YES; }else if didCancel == YES{ //cancelNotifications didCancel = NO; }