1

我正在构建我的应用程序以在 IOS swift 4 中触发每日、每周和每月通知。通知使用公历完美运行。但是,当我将日期更改为回历(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)")
    }
}
4

3 回答 3

1

将日历类型添加到触发器后它起作用了

trigger = UNCalendarNotificationTrigger(calendar:calendar, dateMatching: components, repeats: true)
于 2017-12-26T18:21:23.563 回答
0

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

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

参照。将 NSDates 从一个日历转换为另一个

于 2017-12-23T18:01:45.207 回答
0

添加.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)
于 2020-11-27T08:24:21.637 回答