Reputation: 1768
I'am trying to schedule a notification every specified date on each year for example every 1/6/yyyy and 15/6/yyyy i've done this code but it does not work
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)
Upvotes: 1
Views: 559
Reputation: 54706
You need to add a notification content as well, otherwise your notification won't get added. You also need to add the specified notification category to your notification centre's categories.
If you have the notification centre request set up and the user grants the request, with below code you can send a notification at a specific date.
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
}
}
Upvotes: 1