How to implement scheduled local notification - ios

I have this code below to test how local notification works every hour. But im not getting anything.
Also, is there a way to send different local notifications messages in different times? and im just calling the LocalNotificationHour() in viewDidLoad()
I just started learning swift, so im sorry in advance.
--
#objc func LocalNotificationHour() {
let user = UNUserNotificationCenter.current()
user.requestAuthorization(options: [.alert,.sound]) { (granted, error) in}
let content = UNMutableNotificationContent()
content.title = "Local Notification"
content.body = "This is a test."
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = 1
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let uuid = UUID().uuidString
let request = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)
user.add(request) { (error) in print("Error")}
}

var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = 1
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
This basically takes todays date and sets the time to 1am. Using: UNCalendarNotificationTrigger(dateMatching: you are telling the notification to trigger at 1am today and then repeat at the same time each day.
To trigger a notification based on a time interval you should use the UNTimeIntervalNotificationTrigger.
// Fire in 60 minutes (60 seconds times 60)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (60*60), repeats: false)

You can schedule your notification for every minute by adding following code:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (success, error) in
if error == nil, !success {
print("Error = \(error!.localizedDescription)")
} else {
let content = UNMutableNotificationContent()
content.title = "Local Notification"
content.body = "This is a test."
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let uuid = UUID().uuidString
let request = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}

Related

Cancel a repeating UNNotification for today only

I am scheduling daily repeating notifications by setting only hour, minutes and seconds:
func addNotification(fireDate: Date)
{
let notificationCenter = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Some title"
content.body = "Some message"
content.sound = .default
content.categoryIdentifier = "MyCategory"
let calendar = Calendar(identifier: .gregorian)
let triggerDate = calendar.dateComponents([.hour, .minute, .second], from: fireDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let requestID = UUID().uuidString
let notificationRequest = UNNotificationRequest(identifier: requestID, content: content, trigger: trigger)
notificationCenter.add(notificationRequest) { error in
if let error = error
{
print(error.localizedDescription)
}
}
}
Now I would like to be able to cancel all notifications for current day, so I could receive notifications starting with tomorrow. I tried to subclass UNCalendarNotificationTrigger in order to change nextTriggerDate, but there is an error when adding a notification using my custom trigger class. Cannot find a way to achieve this, if I cancel a scheduled notification at certain time, I will not receive that notification anymore. Any ideas are appreciated.

Canceling a daily notification one day, but still show the notifications the rest of the days

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)
}
}
}

Local notifications every month except specific date

I have a local notification which repeats every month at a specific day:
func setNotifications(date: Date, forMonth: Bool) {
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
if forMonth == true {
let content = UNMutableNotificationContent()
content.title = ""
content.body = "Here is some nice content."
content.sound = UNNotificationSound.default()
let triggerDate = Calendar.current.dateComponents([.day], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let request = UNNotificationRequest(identifier: "MonthNotification", content: content, trigger: trigger)
center.add(request, withCompletionHandler: nil)
}
}
}
}
Let's say the date is 28.01.2018 you will get a notification at 28.02. and so on...
How can I achieve that this notification not appears at another special date (which has this day), for example 28.05.2018?
I hope my question is clear enough.

Add reminder notification on apple watch with different different repeat interval

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.

Local notifications - repeat Interval in swift 3

I want to repeat local notification every week, before iOS10 there is repeatInterval, but i am not able to find anything suitable to repeat notifications in iOS10.
TimeTrigger and calendarTrigger both have repeat as true or false, where can i apply repeat as weekly, daily, monthly.
Thanks.
Try this.
func scheduleNotification(at date: Date, body: String) {
let triggerWeekly = Calendar.current.dateComponents([.weekday,hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Dont Forget"
content.body = body
content.sound = UNNotificationSound.default()
//content.categoryIdentifier = "todoList"
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)")
}
}
}

Resources