0

I need to make a local notification that alert the user daily at 19:30.

Here is what i did:

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

    let identifier = "daily.alarm"
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
      if error != nil {
        debugPrint("center.add(request, withCompletionHandler: { (error)")
      } 
    })

However, I found that the notification is not alert at 19:30. Instead, it alert 15 mins earlier. Also, it cannot alarm daily as well. What i have done wrong?

user6539552
  • 1,331
  • 2
  • 19
  • 39

1 Answers1

0

Use below function to schedule your notification:

func registerLocal() {
    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Yas!")
        } else {
            print("Ohhh No!!")
        }
    }
}

func scheduleLocal() {
    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Drink Milk"
    content.body = "Two Servings A Day Keeps Bone Problems At Bay."
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "whater"]
    content.sound = UNNotificationSound.default()

    var dateComponents = DateComponents()
    dateComponents.hour = 19
    dateComponents.minute = 30

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

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}
Bhavesh Dhaduk
  • 1,888
  • 15
  • 30
  • I have already done the registerLocal() function, just that i did not post it here as it is not the focus. The above code still won't trigger alert at 1930 daily. – user6539552 Jul 11 '17 at 13:55
  • How you are test @user6539552 – Bhavesh Dhaduk Jul 11 '17 at 18:14
  • It's ok for the first alarm, but it does not repeat!! – user6539552 Jul 13 '17 at 16:55
  • if i have two notification to be scheduled, they are with different identifier and content. I used the code UNUserNotificationCenter.current().removeAllPendingNotificationRequests() will this remove the pending notification of each other? – user6539552 Jul 13 '17 at 17:11