I have the following setup and no notification are firing at all.
Based on other similar questions on the stack, I've put in a unique identifier for each request and I've also added the body to the content.
I've got this function which requests permission from user.
func sendIntNotifications()
{
//1. Request permission from the user
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler:
{
(granted, error) in
if granted
{
print ("Notification access granted")
}
else
{
print(error?.localizedDescription)
}
UNUserNotificationCenter.current().delegate = self
})
// This function has a lot of other code that then calls this function to set multiple notifications :
for daysInt in outputWeekdays
{
scheduleActualNotification(hourInt: hourInt, minuteInt: minuteInt, dayInt: daysInt)
}
}
And these are the main function :
func scheduleActualNotification(hourInt hour: Int, minuteInt minute: Int, dayInt day: Int)
{
// 3.1 create date components for each day
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.day = day
//3.2 Create a calendar trigger for that day at that time
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,
repeats: true)
//3.3 Message content
let content = UNMutableNotificationContent()
content.title = "Test Title"
content.body = "Test body"
content.badge = 1
// 3.4 Create the actual notification
let request = UNNotificationRequest(identifier: "bob \(i+1)",
content: content,
trigger: trigger)
// 3.5 Add our notification to the notification center
UNUserNotificationCenter.current().add(request)
{
(error) in
if let error = error
{
print("Uh oh! We had an error: \(error)")
}
}
}
This function is to receive the notification when this app is open
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert, .sound]) //calls the completionHandler indicating that both the alert and the sound is to be presented to the user
}
There are no errors either lol!
Edit :
So from the user interface, I selected 2350 and Saturday and Sunday. I expect the notification to be sent at 2350 on both Saturday and Sunday.
I did print(daysInt). The first value of it is 1 and the second value of it is 7 which is just as expected. Secondly, I went into the function scheduleActualNotification and the values of hour was 23 and minute was 50, just as expected.
Thank you!
So after weeks of frustration, this is the solution :
Replace dateComponents.day = day with dateComponents.weekday = day. .day is for day of the month whereas .weekday is day of the week!
Also do not use dateComponents.year = 2017 as that caused the notifications not to fire.
The notifications work perfectly fine now!!
Calendar Unit Flags can help you :
var notificationTriggerCalendar : UNCalendarNotificationTrigger? = nil
if let fireDate = trigger.remindAt {
let unitFlags = Set<Calendar.Component>([.hour, .year, .minute, .day, .month, .second])
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents(unitFlags, from: fireDate)
let newDate = Calendar.current.date(from: components)
notificationTriggerCalendar = UNCalendarNotificationTrigger.init(dateMatching: components, repeats: true)
}
Related
I believe this has been asked several times, but there is no clear answer.
There are two ways to schedule temporal notifications: UNCalendarNotification and UNTimeIntervalNotificationTrigger.
Scheduling a notification for a specific time and day of the week is trivial, same with on a day specific of the month, but scheduling for a specific time, every n days is not so trivial.
E.g. Every 5 days at 11:00.
UNTimeIntervalNotificationTrigger may seem like the right class to reach for, except problems are introduced when daylight savings or timezone changes occur. E.g. Summer time ends and now your notification is at 10:00 instead of 11:00.
The day property on the DateComponents class together with the UNCalendarNotification class may hold the solution because it says in the docs "A day or count of days". I interpret this as "A specific day of the month (A day) or n number of days (count of days)".
Digging further into the day property docs, it reads "This value is interpreted in the context of the calendar in which it is used".
How can you use the day property together with the context of the calendar to work with a count of days instead of specific days of the month?
Additionally, the docs for the hour and minute properties in DateComponents also read "An hour or count of hours" and "A minute or count of minutes" respectively. So even if you were to set day to "a count of days" how might you set the hour and minute correctly?
It's clear this functionality is possible in iOS - the Reminders app is evidence of this.
You can set them up upfront using UNCalendarNotificationTrigger for an n number of times and using an adjusted calendar for the current timeZone
import SwiftUI
class NotificationManager: NSObject, UNUserNotificationCenterDelegate{
static let shared: NotificationManager = NotificationManager()
let notificationCenter = UNUserNotificationCenter.current()
private override init(){
super.init()
requestNotification()
notificationCenter.delegate = self
getnotifications()
}
func requestNotification() {
print(#function)
notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
// Handle the error here.
print(error)
}
// Enable or disable features based on the authorization.
}
}
/// Uses [.day, .hour, .minute, .second] in current timeZone
func scheduleCalendarNotification(title: String, body: String, date: Date, repeats: Bool = false, identifier: String) {
print(#function)
let content = UNMutableNotificationContent()
content.title = title
content.body = body
let calendar = NSCalendar.current
let components = calendar.dateComponents([.day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: repeats)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if error != nil {
print(error!)
}
}
}
///Sets up multiple calendar notification based on a date
func recurringNotification(title: String, body: String, date: Date, identifier: String, everyXDays: Int, count: Int){
print(#function)
for n in 0..<count{
print(n)
let newDate = date.addingTimeInterval(TimeInterval(60*60*24*everyXDays*n))
//Idenfier must be unique so I added the n
scheduleCalendarNotification(title: title, body: body, date: newDate, identifier: identifier + n.description)
print(newDate)
}
}
///Prints to console schduled notifications
func getnotifications(){
notificationCenter.getPendingNotificationRequests { request in
for req in request{
if req.trigger is UNCalendarNotificationTrigger{
print((req.trigger as! UNCalendarNotificationTrigger).nextTriggerDate()?.description ?? "invalid next trigger date")
}
}
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.banner)
}
}
class ZuluNotTriggerViewModel:NSObject, ObservableObject, UNUserNotificationCenterDelegate{
#Published var currentTime: Date = Date()
let notificationMgr = NotificationManager.shared
///Sets up multiple calendar notification based on a date
func recurringNotification(title: String, body: String, date: Date, identifier: String, everyXDays: Int, count: Int){
print(#function)
notificationMgr.recurringNotification(title: title, body: body, date: date, identifier: identifier, everyXDays: everyXDays, count: count)
//just for show now so you can see the current date in ui
self.currentTime = Date()
}
///Prints to console schduled notifications
func getnotifications(){
notificationMgr.getnotifications()
}
}
struct ZuluNotTriggerView: View {
#StateObject var vm: ZuluNotTriggerViewModel = ZuluNotTriggerViewModel()
var body: some View {
VStack{
Button(vm.currentTime.description, action: {
vm.currentTime = Date()
})
Button("schedule-notification", action: {
let twoMinOffset = 120
//first one will be in 120 seconds
//gives time to change settings in simulator
//initial day, hour, minute, second
let initialDate = Date().addingTimeInterval(TimeInterval(twoMinOffset))
//relevant components will be day, hour minutes, seconds
vm.recurringNotification(title: "test", body: "repeat body", date: initialDate, identifier: "test", everyXDays: 2, count: 10)
})
Button("see notification", action: {
vm.getnotifications()
})
}
}
}
struct ZuluNotTriggerView_Previews: PreviewProvider {
static var previews: some View {
ZuluNotTriggerView()
}
}
I have this app with a daily notification at 12pm. If the user does something, I want to cancel the notification that day.
Is there a way to cancel the notification that day, but the rest of the days keep working the same?
private func setUpNotification() {
// Ask Permission
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
}
// Create content for notification
let content = UNMutableNotificationContent()
content.title = "I'm a notification!"
content.body = "Don't forget to track your cigarretes!"
// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = 12
dateComponents.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
//Register the request
center.add(request) { (error) in
if error != nil {
// Handle any errors.
print(error?.localizedDescription)
}
}
}
I have setup a local notification system so that I can fire a notification at a certain time every day. This time is determined by the user and I store it as a string. I will break down all the steps I have done in the code to follow but basically, my problem is that the notification won't fire.
Step 1:
In this step I setup an alert to ask permission to send a notification:
let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .badge, .sound]
center.requestAuthorization(options: options) { (granted, error) in
if granted {
application.registerForRemoteNotifications()
}
}
Step 2:
In this step I setup the function I call to send a notification:
static func sendNotification(stringDate: String) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Detail"
content.badge = 1
if let date = dateFormatter.date(from: stringDate) {
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "dateDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}
Step 3:
I then call this function in my app delegate file like so:
func applicationDidEnterBackground(_ application: UIApplication) {
let defaults = UserDefaults.standard
if defaults.object(forKey: "currentUser") != nil {
if User.current.desiredTimeForNews.characters.contains("A") {
let stringToBeConverted = User.current.desiredTimeForNews.replacingOccurrences(of: "AM", with: "")
HelperFunctions.sendNotification(stringDate: stringToBeConverted)
} else {
let stringToBeConverted = User.current.desiredTimeForNews.replacingOccurrences(of: "PM", with: "")
HelperFunctions.sendNotification(stringDate: stringToBeConverted)
}
}
}
IMPORTANT: As you can see within my function I take in a "stringDate" parameter. This variable has a string value of my date. I then convert this to a date value. Through using breakpoints and print statements I have seen that all my values including the date, hour, minute, etc are all NOT nil.
Overall, my problem is that the notification is never sent. However I know for a fact that it is called as I have used breakpoints to prove that. Any help would be appreciated!
For me personally, I ran it on a real device and it worked. Although it should work on a simulator it didn't for me. So I would try and run it on a real device before looking at anything else!
The code seems to be ok. Should work on the device and also on the simulator. My guess is that the trigger time just happens at a different time, then what you would expect.
Insert this check below after your setup to see the details:
UNUserNotificationCenter.current()
.getPendingNotificationRequests(completionHandler: { requests in
for (index, request) in requests.enumerated() {
print("notification: \(index) \(request.identifier) \(request.trigger)")
}
})
note 1:Why do you have this line in the code?
application.registerForRemoteNotifications()
note 2:You should check if the requestAuthorization went through ok. With something like this:
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
guard (settings.authorizationStatus == .authorized )
else { print("notifsetup not authorized");return }
guard (settings.soundSetting == .enabled) else {
print("notifsetup sound not enabled");return }
}
I am trying to create a timer which triggers a local notification to go off at a time that the user has set. The issue I am having is that I cannot figure out a way to be able to set the local notification to go off at say 7:00PM. Almost all the methods found when researching this issue involved the local notification going off at a certain amount of time from the current date. I am trying to allow the user to select 7:00PM and then have the notification go off at that time. Logically it makes sense that this can be achieved through having the final time (selected value by the user) - current time which would give you the time difference. I am however not entirely sure how to do this.
Any help with regard to the topic will be very much appreciated, thank you. Below is the code which I am currently using to trigger a local notification.
let center = UNUserNotificationCenter.current()
content.title = storedMessage
content.body = "Drag down to reset or disable alarm"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.init(named: "1.mp3")
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeAmount, repeats: false)
let request = UNNotificationRequest(identifier: "requestAlarm", content: content, trigger: trigger)
center.add(request)
center.delegate = self
Well in iOS 10 Apple has deprecated UILocalNotification which means it is time to get familiar with a new notifications framework.
Setup
This is a long post so let’s start easy by importing the new notifications framework:
// Swift
import UserNotifications
// Objective-C (with modules enabled)
#import UserNotifications;
You manage notifications through a shared UNUserNotificationCenter object:
// Swift
let center = UNUserNotificationCenter.current()
// Objective-C
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
Authorization
As with the older notifications framework you need to have the user’s permission for the types of notification your App will use. Make the request early in your App life cycle such as in application:didFinishLaunchingWithOptions:. The first time your App requests authorization the system shows the user an alert, after that they can manage the permissions from settings:
// Swift
let options: UNAuthorizationOptions = [.alert, .sound];
// Objective-C
UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound;
You make the actual authorization request using the shared notification center:
// Swift
center.requestAuthorization(options: options) { (granted, error) in
if !granted {
print("Something went wrong")
}
}
// Objective-C
[center requestAuthorizationWithOptions:options
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
NSLog(#"Something went wrong");
}
}];
The framework calls the completion handler with a boolean indicating if the access was granted and an error object which will be nil if no error occurred.
Note: The user can change the notifications settings for your App at any time. You can check the allowed settings with getNotificationSettings. This calls a completion block asynchronously with a UNNotificationSettings object you can use to check the authorization status or the individual notification settings:
// Swift
center.getNotificationSettings { (settings) in
if settings.authorizationStatus != .authorized {
// Notifications not allowed
}
}
// Objective-C
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) {
// Notifications not allowed
}
}];
Creating A Notification Request
A UNNotificationRequest notification request contains content and a trigger condition:
Notification Content
The content of a notification is an instance of the UNMutableNotificationContent with the following properties set as required:
title: String containing the primary reason for the alert.
subtitle: String containing an alert subtitle (if required)
body: String containing the alert message text
badge: Number to show on the app’s icon.
sound: A sound to play when the alert is delivered. Use UNNotificationSound.default() or create a custom sound from a file.
launchImageName: name of a launch image to use if your app is launched in response to a notification.
userInfo: A dictionary of custom info to pass in the notification
attachments: An array of UNNotificationAttachment objects. Use to include audio, image or video content.
Note that when localizing the alert strings like the title it is better to use localizedUserNotificationString(forKey:arguments:) which delays loading the localization until the notification is delivered.
A quick example:
// Swift
let content = UNMutableNotificationContent()
content.title = "Don't forget"
content.body = "Buy some milk"
content.sound = UNNotificationSound.default()
// Objective-C
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = #"Don't forget";
content.body = #"Buy some milk";
content.sound = [UNNotificationSound defaultSound];
Notification Trigger
Trigger a notification based on time, calendar or location. The trigger can be repeating:
Time interval: Schedule a notification for a number of seconds later. For example to trigger in five minutes:
// Swift
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false)
// Objective-C
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:300
repeats:NO];
Calendar: Trigger at a specific date and time. The trigger is created using a date components object which makes it easier for certain repeating intervals. To convert a Date to its date components use the current calendar. For example:
// Swift
let date = Date(timeIntervalSinceNow: 3600)
let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
// Objective-C
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3600];
NSDateComponents *triggerDate = [[NSCalendar currentCalendar]
components:NSCalendarUnitYear +
NSCalendarUnitMonth + NSCalendarUnitDay +
NSCalendarUnitHour + NSCalendarUnitMinute +
NSCalendarUnitSecond fromDate:date];
To create the trigger from the date components:
// Swift
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
// Objective-C
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate
repeats:NO];
To create a trigger that repeats at a certain interval use the correct set of date components. For example, to have the notification repeat daily at the same time we need just the hour, minutes and seconds:
let triggerDaily = Calendar.current.dateComponents([hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
To have it repeat weekly at the same time we also need the weekday:
let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
Scheduling
With both the content and trigger ready we create a new notification request and add it to the notification center. Each notification request requires a string identifier for future reference:
// Swift
let identifier = "UYLLocalNotification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
}
})
// Objective-C
NSString *identifier = #"UYLLocalNotification";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content trigger:trigger]
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Something went wrong: %#",error);
}
}];
To launch notification on specific time use below code.
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default()
let gregorian = Calendar(identifier: .gregorian)
let now = Date()
var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)
// Change the time to 7:00:00 in your locale
components.hour = 7
components.minute = 0
components.second = 0
let date = gregorian.date(from: components)!
let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: CommonViewController.Identifier, content: content, trigger: trigger)
print("INSIDE NOTIFICATION")
UNUserNotificationCenter.current().add(request, withCompletionHandler: {(error) in
if let error = error {
print("SOMETHING WENT WRONG")
}
})
And to launch constantly in specific time interval for example after every 2 minutes use below line for trigger.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120, repeats: true)
For Swift You can possibly Use this Code:
let calendar = Calendar.current
let components = DateComponents(year: 2018, month: 05, day: 06, hour: 20, minute: 22) // Set the date here when you want Notification
let date = calendar.date(from: components)
let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date!)
let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Notification Demo"
content.subtitle = "Demo"
content.body = "Notification on specific date!!"
let request = UNNotificationRequest(
identifier: "identifier",
content: content,
trigger: trigger
)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
if error != nil {
//handle error
} else {
//notification set up successfully
}
})
Hope this Help.
This is the simplest way to add a notification at a specific time, and it is based off of Apple's Developer Documentation: https://developer.apple.com/documentation/usernotifications
Here is my implementation in a modular function:
public func simpleAddNotification(hour: Int, minute: Int, identifier: String, title: String, body: String) {
// Initialize User Notification Center Object
let center = UNUserNotificationCenter.current()
// The content of the Notification
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
// The selected time to notify the user
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = hour
dateComponents.minute = minute
// The time/repeat trigger
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// Initializing the Notification Request object to add to the Notification Center
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
// Adding the notification to the center
center.add(request) { (error) in
if (error) != nil {
print(error!.localizedDescription)
}
}
}
try this
let dateformateer = NSDateFormatter()
dateformateer.timeStyle = .ShortStyle
let notification = UILocalNotification()
var datecomponent = NSDateComponents()
datecomponent = NSCalendar.currentCalendar().components([NSCalendarUnit.Day,NSCalendarUnit.Month,NSCalendarUnit.Hour,NSCalendarUnit.Year, NSCalendarUnit.Minute],fromDate: Datepicker.date)
var fixdate = NSDate()
fixdate = NSCalendar.currentCalendar().dateFromComponents(datecomponent)!
notification.fireDate = fixdate
notification.alertTitle = "Title"
notification.alertBody = "Body"
UIApplication.sharedApplication().scheduleLocalNotification(notification)`
I've noticed that if I create an UNCalendarNotificationTrigger with a custom date it does't get added unless i put:
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: **true**)
Apple Example is:
let date = DateComponents()
date.hour = 8
date.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
which make sense to be repeats == true.
In my scenario I dont need to create one notification that gets repeated many times, but I need multiple notificaitons fired only once on a specific calendar date (which is of course in the future)..
If I'm doing:
let calendar = Calendar(identifier: .gregorian)
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
let newdate = formatter.date(from: "20161201")
let components = calendar.dateComponents(in: .current, from: newdate!)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
then i always get 0 pending notifications...
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (notifications) in
print("num of pending notifications \(notifications.count)")
})
num of pending notification 0
Any idea?
EDIT1:
Adding other context as pointed out by one of the answers.
I'm actually adding the request to the current UNUserNotificationQueue.
let request = UNNotificationRequest(identifier: "future_calendar_event_\(date_yyyyMMdd)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
// Do something with error
print(error.localizedDescription)
} else {
print("adding \((request.trigger as! UNCalendarNotificationTrigger).dateComponents.date)")
}
}
I have the same problem and I solve it now. It is due to dateComponents' year.
In order to solve this problem, I test the following code:
1.
let notificationCenter = UNUserNotificationCenter.current()
let notificationDate = Date().addingTimeInterval(TimeInterval(10))
let component = calendar.dateComponents([.year,.day,.month,.hour,.minute,.second], from: notificationDate)
print(component)
let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)
let request = UNNotificationRequest(identifier: item.addingDate.description, content: content, trigger: trigger)
self.notificationCenter.add(request){(error) in
if let _ = error {
assertionFailure()
}
}
In console, print component:
year: 106 month: 2 day: 14 hour: 12 minute: 3 second: 42 isLeapMonth: false
And in this case, the notification cannot be found in pending notification list.
2.When I set component's year explicitly to 2017:
let notificationDate = Date().addingTimeInterval(TimeInterval(10))
var component = calendar.dateComponents([.year,.day,.month,.hour,.minute,.second], from: notificationDate)
component.year = 2017
print(component)
let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)
let request = UNNotificationRequest(identifier: item.addingDate.description, content: content, trigger: trigger)
self.notificationCenter.add(request){(error) in
if let _ = error {
assertionFailure()
}
}
In console, the component is:
year: 2017 month: 2 day: 14 hour: 12 minute: 3 second: 42 isLeapMonth: false
Then this notification can be found in pending notification list.
And next, I check in the pending notification requests to find whether the trigger-date's year component is 106 or 2017:
notificationCenter.getPendingNotificationRequests(){[unowned self] requests in
for request in requests {
guard let trigger = request.trigger as? UNCalendarNotificationTrigger else {return}
print(self.calendar.dateComponents([.year,.day,.month,.hour,.minute,.second], from: trigger.nextTriggerDate()!))
}
}
I find the trigger's nextTriggerDate components are:
year: 106 month: 2 day: 14 hour: 12 minute: 3 second: 42 isLeapMonth: false
Conclusion
So if you want to set the trigger's repeats to false, you should make sure the trigger date is bigger than current date.
The default dateComponents' year may be unsuitable, such as 106. If you want the notification to fire in 2017, you should set the components year to 2017 explicitly.
Perhaps this is a bug, because I set trigger's dateComponents' year to 2017 but get 106 in nextTriggerDate of pending notification request.
On my app, I request permission after notification set by mistake. So If I want to get pending notification count, I got 0.
I requested permission on AppDelegate but notifications setted on first view viewdidload(). I added a notification function to trigger with button. After get permission click button and finally setted my notification and I got pending notification count 1.
I hope that's will help you.
UNCalendarNotificationTrigger creates the schedule for which a notification should occur, but it does not do the scheduling. For this you need to create a UNNotificationRequest and then add this to the notification center. Something along the lines of:
let request = UNNotificationRequest(identifier: "MyTrigger", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
// Do something with error
} else {
// Request was added successfully
}
}