使用开关启用和禁用本地通知(swift 3)

Jav*_*ras 2 uiswitch ios uilocalnotification swift3

我正在制作我的第一个应用程序,其中一个功能是待办事项列表。我有一个开关,当它关闭时禁用本地通知,当它打开时,它应该在开关打开时启用它们。我使用 保存开关状态UserDefaults,通知确实出现,但是,即使我指定它们应该它们也不会重复。现在我将通知设置为每 60 秒重复一次以进行测试,但是当它起作用时将需要两天时间。只要开关打开,如何使通知重复?我的开关代码:

@IBOutlet weak var switchout: UISwitch!

@IBAction func notifswitch(_ sender: Any) {
print ("hello")
    if switchout.isOn
    {
        if #available(iOS 10.0, *), list.isEmpty == false {

            let content = UNMutableNotificationContent()
            content.title = "You have tasks to complete!"
            content.subtitle = ""
            content.body = "Open the task manager to see which tasks 
need completion"
            let alarmTime = Date().addingTimeInterval(60) 
            let components = Calendar.current.dateComponents([.weekday, 
.hour, .minute], from: alarmTime)
            let trigger = UNCalendarNotificationTrigger(dateMatching: 
components, repeats: true)
            let request = UNNotificationRequest(identifier: 
"taskreminder", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request, 
withCompletionHandler: nil)
        } else {
            print ("hello")
        }

    } else
    {
        UIApplication.shared.cancelAllLocalNotifications()
    }

    self.saveSwitchesStates()
Run Code Online (Sandbox Code Playgroud)

Mic*_*ann 7

我怀疑您使用了错误的取消 API。

代替:

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

尝试使用:

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
Run Code Online (Sandbox Code Playgroud)

不过,这会取消您的应用程序的所有内容。如果你想做特定的通知,你可以这样做:

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: "taskreminder")
Run Code Online (Sandbox Code Playgroud)

在这个密切相关的问题中可以看到更多信息。

2)

现在关于你的通知不重复,即使你在设置true触发器时已经设置,我看到你设置的时间需要匹配 for [.weekday, .hour, .minute],这意味着它会在一周中的每一天重复时间。

尝试通过UNNotificationRequest代替:

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
Run Code Online (Sandbox Code Playgroud)