Repeating Local Notification Daily at a Set Time with Swift

Repeating local notification daily at a set time with swift

You have to provide an NSCalendarUnit value like “HourCalendarUnit” or “DayCalendarUnit” for repeating a notification.

Just add this code to repeat the local notification daily :

notification.repeatInterval = NSCalendarUnit.CalendarUnitDay

How do I set up a repeating daily notification with different content each time?

Ok, here is the solution for this.

It is NOT possible to schedule a repeating notification with a random content each day. The content is defined when the notification is scheduled, and cannot be changed later.

What you CAN do it schedule up to 64 notifications in advance though. So you can schedule 64 unique notifications for the next 64 days, and then whenever you open the app check how many remain, and fill up the notification-schedule up to 64 again.

If you don't open the app after 64 days the notifications stop coming though :P

How Can I Repeat Local Notifications for Evey Hours in Every Day?

let interval:TimeInterval = 60.0 // 1 minute = 60 seconds

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: true)

Use UNTimeIntervalNotificationTrigger instead of UNCalendarNotificationTrigger because UNCalendarNotificationTrigger object is used when you want to schedule the delivery of a local notification at the specified date and time and UNTimeIntervalNotificationTrigger object is used when you want to schedule the delivery of a local notification after the specified number of seconds elapse.

https://developer.apple.com/documentation/usernotifications/untimeintervalnotificationtrigger

I want to set a daily reminder (local notification) and also a reminder 10 seconds after the user enters a button

This is how you do it: Convert current date (when you tap on a button) into date components and schedule a notification for that particular time every day.

let center = UNUserNotificationCenter.current()

let content = UNMutableNotificationContent()
content.title = "Facts, tips, and tricks to help you quit:"
content.body = reminders.randomElement()!
content.sound = .default
content.userInfo = ["value": "Data with local notification"]

let date = Date()
let calendar = Calendar.current

let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)

var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = second
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

let request = UNNotificationRequest(identifier: "reminder", content: content, trigger: trigger)
center.add(request)


Related Topics



Leave a reply



Submit