使用非公历日历创建UNNotification

时间:2017-12-23 17:55:32

标签: ios time calendar usernotifications

我正在构建我的应用程序以在IOS swift 4中发送每日,每周和每月通知。通知使用公历完美地工作。但是,当我将日期更改为Hijri日历(日历(标识符:.islamicUmmAlQura)时,它不是wrk。它接缝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)")
    }
}

}

当我使用(日历(标识符:.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)")
    }
}

3 个答案:

答案 0 :(得分:1)

将日历类型添加到触发器

后,它可以正常工作
trigger = UNCalendarNotificationTrigger(calendar:calendar, dateMatching: components, repeats: true)

答案 1 :(得分:0)

如果UserNotifications框架期望在某个日历中解释DateComponents,那么这就是您必须使用的日历。这并不意味着潜在的日期时间会发生变化,或者是不正确的。

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

比照。 Convert NSDates from one calendar to another

答案 2 :(得分: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)