gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:58:05 25 4
gpt4 key购买 nike

我正在制作我的第一个应用程序,其中一个功能是待办事项列表。我有一个开关,它在关闭时会禁用本地通知,而在打开时,只要开关打开,就应该启用它们。我使用 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()

最佳答案

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

而不是:

UIApplication.shared.cancelAllLocalNotifications()

尝试使用:

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

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

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: "taskreminder")

更多信息can be seen at this closely related question

2)

现在,关于您的通知不重复,即使您在设置触发器时设置了 true,我发现您设置的时间需要与 [ .weekday, .hour, .min],这意味着它将在一周中的每一天同时重复。

尝试将 THIS 传递给 UNNotificationRequest:

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)

关于ios - 使用开关启用和禁用本地通知(swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44274223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com