我的 Apple Watch 应用程序中有本地通知。在 houser 中设置间隔和保存按钮也有效。唯一不起作用的是显示随机消息。它从 randomText() 函数中选择三个之一,然后每隔“间隔”时间重复一个... 这是一个文件。
import SwiftUI
import UserNotifications
struct Nottie2: View {
@AppStorage("notificationInterval") var notificationInterval: Int = 1
@AppStorage("isSnoozed") var isSnoozed: Bool = false
@AppStorage("isNotificationsEnabled") var isNotificationsEnabled: Bool = false
@State private var borderColor = Color.orange
@State private var buttonText = "Save"
var body: some View {
VStack {
Toggle(isOn: $isNotificationsEnabled) {
if isNotificationsEnabled {
Text("Turn off")
}else {
Text("Turn on")
}
}
.padding()
.onChange(of: isNotificationsEnabled) { enabled in
if enabled {
requestPermission()
} else {
disableNotification()
}
}
if isNotificationsEnabled {
Picker("Notification Interval", selection: $notificationInterval) {
ForEach(1...6, id: \.self) { interval in
Text("\(interval) hour\(interval > 1 ? "s" : "")")
}
}.frame(height: 60)
.padding()
Button(action: {
enableNotification()
self.buttonText = "Saving"
self.borderColor = .green
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.buttonText = "Saved"
self.borderColor = .green
}
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
self.buttonText = "Save"
self.borderColor = .orange
}
})
{
Text(buttonText)
}.foregroundColor(.white)
.padding(1)
.frame(width: 75)
.padding(7)
.overlay(
RoundedRectangle(cornerRadius: 25)
.stroke(borderColor, lineWidth: 2))
.buttonStyle(.plain)
}
}
.onAppear() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("Permission granted")
} else {
print("Permission denied")
isNotificationsEnabled = false
}
}
}
.onReceive(NotificationCenter.default.publisher(for: WKExtension.applicationDidBecomeActiveNotification)) { _ in
if isSnoozed {
enableNotification(snooze: true)
}
}
}
请求通知权限的功能
private func requestPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("Permission granted")
enableNotification()
} else {
print("Permission denied")
isNotificationsEnabled = false
}
}
}
randomText() 被调用。我认为问题出在这里。我认为它(我不知道如何)在关闭后清除通知
private func enableNotification(snooze: Bool = false) {
let content = UNMutableNotificationContent()
// content.title = "Notification Title"
content.body = randomText()
content.sound = UNNotificationSound.default
var trigger: UNNotificationTrigger
if snooze {
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 540, repeats: false)
} else {
trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(notificationInterval * 3600), repeats: true)
}
let request = UNNotificationRequest(identifier: "notification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
带有随机通知文本的小数组的功能。
func randomText() -> String {
let words = ["Place", "Cat", "House"]
return words[Int(arc4random_uniform(UInt32(words.count)))]
}
其余的通知操作。
private func disableNotification() {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["notification"])
}
private func snoozeNotification() {
isSnoozed = true
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["notification"])
enableNotification(snooze: true)
}
private func dismissNotification() {
isSnoozed = false
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["notification"])
}
private func showNotificationActions() {
let snoozeAction = UNNotificationAction(identifier: "snooze", title: "Snooze", options: [])
let dismissAction = UNNotificationAction(identifier: "dismiss", title: "Dismiss", options: [.destructive])
let category = UNNotificationCategory(identifier: "notificationActions", actions: [snoozeAction, dismissAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
}
}
struct Nottie2_Previews: PreviewProvider {
static var previews: some View {
Nottie2()
}
}