为什么我的通知不能在Swiftui上工作



我在GitHub上传了我的项目,我需要帮助我的通知,他们不工作,我不明白为什么。所以我有时间间隔祈祷,我需要本地通知每次开始祈祷时间。

https://github.com/kamilproo/PrayerTime4/tree/main/PrayerKitBetaTest

我的项目)

错误在NotificationViewModel

let interval = -times.isha.timeIntervalSinceNow
guard interval > 0 else {
return
}

它总是返回,因为区间是负的。通知中心不添加通知。

实际上我不知道你的商业案例,但它可以是这样的:

func scheduleNotification(times: PrayerTimes) { func scheduleNotification(times: PrayerTimes) {
...
let triggerDate = getTriggerDate(date: times.isha, timeIntervalMinutes: 1)
let trigger = UNCalendarNotificationTrigger(
dateMatching: triggerDate,
repeats: false
)
...
}

这是一个辅助函数,你可以在这里传递你的日期和间隔

private func getTriggerDate(date: Date, timeIntervalMinutes: Int) -> DateComponents {
// let triggerDate =  date.addingTimeInterval(Double(-timeIntervalMinutes * 60)) // notification will show 1 minute before date
// return Calendar.current.dateComponents([.timeZone, .year, .month, .day, .hour, .minute], from: triggerDate)
let triggerDate =  Date().addingTimeInterval(10) // notification will show in 10 sec
return Calendar.current.dateComponents([.timeZone, .year, .month, .day, .hour, .minute, .second], from: triggerDate)
}

当你的应用程序处于前台时,你还需要这个来接收通知

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .badge, .sound])
}

最新更新