Is there any way to schedule local notification which fires at specific date and the repeats every minute?
Example: user receive first notification at 8:00 AM and then 8:01, 8:02...
To schedule repeated notification you need date components in trigger initialization.
e.g.
let date = Date(timeIntervalSinceNow: 3600)
let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
trigger repeats notification daily
try to setup trigger using only .second in date components
let date = Date(timeIntervalSinceNow: 3600)
let triggerDaily = Calendar.current.dateComponents([.second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
Related
Im trying to make an app and at 9am I want to call a function and send an a notification. Then another at 12pm, and another at 6pm. Everyday. Does anyone know the best way how?
Use a UNCalendarNotificationTrigger :
var dateComponents = DateComponents()
dateComponents.hour = 9
dateComponents.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,
repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString,
content: YourContent,
trigger: trigger)
In the app I'm developing, there is an option for triggering notification x amount of time before the actual time set for the said notification. For example I set the reminder for 10:00. But in the app's local settings, I set the notification to trigger 10 minutes before the time set. So, in this example's case, the notification will trigger in 9:50.
Now, I can do the above when I'm setting time for individual notification. But what I want to do is trigger all pending notifications before the actual time set for it.
This is the function I'm using to set notifications:
func scheduleNotification(at date: Date, identifier: String, threadIdentifier: String, body: String) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, year: components.year, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "TestNotification"
content.body = body
content.threadIdentifier = threadIdentifier
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {
error in
if let error = error {
print("Error in delivering notification. Error: \(error.localizedDescription)")
}
}
}
The date is coming from the date set by the date picker. I tried to change trigger properties by using this code:
UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
for request in requests {
request.trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10*60, repeats: false)
}
}
But now I get an error saying 'trigger' is a get-only property.
There is no way to change fire time of a scheduled notification , you can remove all of them and re-schedule again
Working on an alarm app and trying to repeat alarm weekly using the below code:
if repeatWeekly {
let triggerWeekly = (Calendar.current as NSCalendar).components([.weekOfYear, .hour, .minute, .second], from: currentDateTime)
trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
} else {
let triggerDaily = (Calendar.current as NSCalendar).components([.hour,.minute,.second,], from: currentDateTime)
trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: false)
}
In iOS9 using UILocalNotification it is working fine with the following code:
let localNotification = UILocalNotification()
localNotification.repeatInterval = NSCalendar.Unit.weekOfYear
But in iOS10 using UNUserNotification repeat local notification doesn't work properly, it only repeats for 1 week and never shows up for the next week.
For example, if current date time is "1 Sept 2017" then notification will be repeated for "8 Sept 2017" but not repeated for 15 Sept, 22 Sept or so on.
Thanks
I am working on an apple watch app where I need reminder user notifications to awake user.
I am able to Set UserNotification with make repeat: true and it will remind the user every day.
But what I need is on single-day app will notify as per user selection like below.
if the user selects 3 min ideal time that every 3 min user got a notification with a vibration on the watch.
same with 5 min, 10 min, and 15 min.
I am using the below code for UserNotification.
func scheduleNotification(at date: Date) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Test Reminder"
content.body = "Show More detail in Body!"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "myCategory"
if let path = Bundle.main.path(forResource: "logo", ofType: "png") {
let url = URL(fileURLWithPath: path)
do {
let attachment = try UNNotificationAttachment(identifier: "logo", url: url, options: nil)
content.attachments = [attachment]
} catch {
print("The attachment was not loaded.")
}
}
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
By using the below trigger with repeats: true
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
it's repeating on next day same time.
Is there any way or method to set repeat after the specified interval as per user selection?
Any help will be appreciated!
Thanks in advance.
Try using a UNTimeIntervalNotificationTrigger instead of a UNCalendarNotificationTrigger.
For example:
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2*60, repeats: true)
That would create a trigger that fires every 2 minutes. timeInterval is the number of seconds between firing each 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
}
}