使用非公历创建 UNNotification

Creating UNNotification with non Gregorian Calendar

我正在构建我的应用程序以在 IOS swift 中触发每日、每周和每月的通知 4. 通知使用公历完美运行。但是,当我将日期更改为 Hijri 日历 (Calendar(identifier: .islamicUmmAlQura) 它不会工作。它接缝 UNCalendarNotificationTrigger 将任何日期转换为公历。 以下每月通知代码在使用公历时完美运行:

func myNotification(at date: Date, withTitle title:String, andBody body:String, notificationIdentifier:String) {

let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.day,.hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.init(named: "notificationSound.wav")
let request = UNNotificationRequest(identifier: notificationIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notificationIdentifier])
UNUserNotificationCenter.current().add(request) {(error) in
    if let error = error {
        print(" error: \(error)")
    }
}

}

当我使用 (Calendar(identifier: .islamicUmmAlQura) 将日期转换为伊斯兰日期时,以下代码不起作用:

func myNotification(at date: Date, withTitle title:String, andBody body:String, notificationIdentifier:String) {

let calendar = Calendar(identifier: .islamicUmmAlQura)
let components = calendar.dateComponents([.day,.hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.init(named: "notificationSound.wav")
let request = UNNotificationRequest(identifier: notificationIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notificationIdentifier])
UNUserNotificationCenter.current().add(request) {(error) in
    if let error = error {
        print(" error: \(error)")
    }
}

如果 UserNotifications 框架期望 DateComponents 在特定日历中解释,那么这就是您必须使用的日历。这并不意味着基础日期时间会更改或不正确。

一个Date只是时间轴上的一个点。时间线如何划分和命名是日历的功能,但 Date 本身不知道也不关心。无论您选择何种描述或分解,时间轴上的点都保持不变。

比照。 Convert NSDates from one calendar to another

将日历类型添加到触发器后有效

trigger = UNCalendarNotificationTrigger(calendar:calendar, dateMatching: components, repeats: true)

.calendar 添加到组件,这将使 UNCalendarNotificationTrigger 使用您的日历计算日期。

let date = Date()
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.calendar, .day, .hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)