0

I want to send a local notification every 8 hours starting at specific time. For example, now we are at 10 o'clock in the morning, but I want you to notify me every 8h starting at 12 o'clock, how I can do that.

I have this code:

let content: UNMutableNotificationContent = UNMutableNotificationContent()
content.title = "Alert!"
content.body = "Alert"
content.categoryIdentifier = "alarm"

let request = UNNotificationRequest(
    identifier: "AA",
    content: content,
    trigger: UNTimeIntervalNotificationTrigger(timeInterval: 8*3600, repeats: false)
)

let action = UNNotificationAction(identifier: "remindLater", title: "remind_me_later".localized(), options: [])
let category = UNNotificationCategory(identifier:"pill-alarm", actions: [action], intentIdentifiers: [], options: [])

UNUserNotificationCenter.current().setNotificationCategories([category])
UNUserNotificationCenter.current().add(request)
SGDev
  • 2,256
  • 2
  • 13
  • 29
Arnau
  • 1

2 Answers2

0

So i had the same problem what i end up doing was:

Let's say you have an alarm every 8 hours, starting at 12 and now is 10AM well i did some calculations and created several repeating notifications:

first Notification will be everyday at 12, second Notification will be everyday at 20, third Notification will be everyday at 4.

you create them like this:

var date = DateComponents()
date.hour = hour
date.minute = minutes

let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)

let request = UNNotificationRequest(identifier: notificationId, content: content, trigger: trigger)

center.add(request) { (error) in
    if let error = error {
        print("Error \(error.localizedDescription)")
    }
}

You need to set diferent identifiers to them, so you can do first,second,third or numerate them. this will help you if you need to cancel them at some point.

Jorge Balleza
  • 897
  • 7
  • 10
-1

First you need to create a trigger date instead of time interval

Like this :

let date = Date(timeIntervalSinceNow:  8*3600 + extraTime) // extraTime = time interval between 8 to 12
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: date)

Now use trigger date in request

let request = UNNotificationRequest(
    identifier: "AA",
    content: content,
    trigger: UNTimeIntervalNotificationTrigger(timeInterval: triggerDate, repeats: false)
)

for more reference : https://useyourloaf.com/blog/local-notifications-with-ios-10/

SGDev
  • 2,256
  • 2
  • 13
  • 29