【发布时间】:2021-08-02 04:47:16
【问题描述】:
我创建了一段代码来在下午 3 点发送本地通知,用户可以使用拨动开关来切换它。我使用 AppStorage 包装器来记住它所处的状态。代码一直有效,直到我打开和关闭开关(模拟用户是否多次切换)以及我切换开关的次数,相同的数字是通知(即我切换 5 次,我一次收到 5 个通知)。这是代码
struct trial: View {
@AppStorage("3") var three = false
func firstNotify() {
let content = UNMutableNotificationContent()
content.title = "It is 3pm"
content.subtitle = "Read the Prime Hour"
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "notifysound.wav"))
// content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "notifysound"))
var dateComponents = DateComponents()
dateComponents.hour = 15
dateComponents.minute = 00
dateComponents.second = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// add our notification request
UNUserNotificationCenter.current().add(request)
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("All set!")
} else if let error = error {
print(error.localizedDescription)
}
}
}
@State private var name: String = "Tim"
var body: some View {
VStack {
Toggle(isOn: $three) {
Text("3 pm")
}
.padding(.horizontal)
.onChange(of: three) { newValue in
if newValue {
firstNotify()
}
}
}
}
}
struct trial_Previews: PreviewProvider {
static var previews: some View {
trial()
}
}
我认为正在发生的事情是 func 没有读取开关是打开还是关闭,而是在每次打开开关时添加一个通知。有谁知道这个问题的解决方案吗???
【问题讨论】: