1

我正在尝试在每年的每个指定日期安排通知,例如每 1/6/yyyy 和 15/6/yyyy 我已经完成了此代码,但它不起作用

    var dateComponents = DateComponents()
        dateComponents.hour = 07
        dateComponents.minute = 24
        dateComponents.month=06;
        dateComponents.day=28;



        let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats:true)
        let request     = UNNotificationRequest.init(identifier: UUID().uuidString, content: content, trigger: trigger)


        let center = UNUserNotificationCenter.current()
        center.add(request)
4

1 回答 1

1

您还需要添加通知内容,否则您的通知将不会被添加。您还需要将指定的通知类别添加到通知中心的类别中。

如果您设置了通知中心请求并且用户批准了请求,则可以使用以下代码在特定日期发送通知。

var dateComponents = DateComponents()
dateComponents.hour = 07
dateComponents.minute = 24
dateComponents.month=06;
dateComponents.day=28;
dateComponents.timeZone = TimeZone.current
let yourFireDate = Calendar.current.date(from: dateComponents)
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey:
            "Your notification title", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Your notification body", arguments: nil)
content.categoryIdentifier = "Your notification category"
content.sound = UNNotificationSound.default()
content.badge = 1

let dateComponents = Calendar.current.dateComponents(Set(arrayLiteral: Calendar.Component.month, Calendar.Component.day, Calendar.Component.hour,Calendar.Component.minute), from: yourFireDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: "Your notification identifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if let error = error {
            //handle error
        } else {
            //notification set up successfully
        }
}
于 2017-06-28T16:36:47.663 回答