如何取消 swift 中的特定 UILocalNotification?

how to cancel a paticular UILocalNotification in swift?

我在 table 视图中有一个单元格,其中有一个用于安排通知的按钮。是否可以删除或取消该特定单元格的通知而不影响其他单元格安排的通知?我想使用相同的按钮删除或取消特定通知。 如果是这样,请帮我提供示例 swift 代码。

@IBAction func setNotification(sender: UIButton!) {

        cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: sender.tag, inSection: 0)) as! CustomTableViewCell
        if sender.selected {

            sender.selected = false
             }else {
currentRegion = CLCircularRegion(center: CLLocationCoordinate2D(latitude: latitude ,longitude:longitude), radius: radius, identifier: identifier)
regionMonitor()
            manager.stopUpdatingLocation()
            sender.selected = true } }

didEnterRegion()

代码
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
            localNotification.regionTriggersOnce = true
            localNotification.alertBody = "you have reached"
            UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
            NSLog("Entering region") }

您可以为 userInfo 中的每个 UILocalNotification 保存一个唯一标识符,然后循环遍历它们以找到唯一 ID 并将其删除:

var app:UIApplication = UIApplication.shared
    if let localNotifications = app.scheduledLocalNotifications {
        for oneEvent in localNotifications {
            var notification = oneEvent as UILocalNotification
            if let userInfoCurrent = notification.userInfo as? [String:AnyObject],
                let uid = userInfoCurrent["uid"] as? String {
                if uid == uidtodelete {
                    //Cancelling local notification
                    app.cancelLocalNotification(notification)
                    break
                }
            }
        }
    }

已更新至 Swift 3 并进行了改进以防止 nil 崩溃

您可以使用NSUserDefaults保存设置。

启用或禁用 didSelectRowAtIndexPath 方法中的设置:

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "ShouldShowRegionEnteredNotification") //true or false

然后你可以这样检查设置:

func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {

    if (NSUserDefaults.standardUserDefaults().boolForKey("ShouldShowRegionEnteredNotification"))
    {
        localNotification.regionTriggersOnce = true
        localNotification.alertBody = "you have reached"
        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
        NSLog("Entering region")
    }
}