每个指定日期IOS 10+重复通知

时间:2017-06-28 14:31:50

标签: ios swift uilocalnotification unusernotificationcenter unnotificationrequest

我试图在每年的每个指定日期安排通知 例如每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)

1 个答案:

答案 0 :(得分: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
        }
}