简体   繁体   中英

Swift 4 Repeating Local Notifications

I am trying it make a notification that will trigger every day at the same time (7:00AM). I am able to get the notification to trigger if I use UNTimeIntervalNotificationTrigger but not UNCalendarNotificationTrigger which is what I really want. This is what I have currently:

In AppDelegate.swift I have:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in
        if error != nil {
            print(error as Any)
        }
    }

    return true
}

And I remembered to import UserNotifications too

When the user presses a button in ViewController.swift this is run:

let content = UNMutableNotificationContent()
    content.title = "Do your daily review"
    content.badge = 1

    let triggerTime = DateComponents.init(hour: 7, minute: 0, second: 0)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerTime, repeats: true)

    let request = UNNotificationRequest(identifier: "dailyNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil

Could you please explain to me what is wrong here, and why UNTimeIntervalNotificationTrigger works but UNCalendarNotificationTrigger doesn't?

I am not sure if it will fix your issue but you are setting a DateComponent directly from an init. I would propose you to do it by initializing an empty DateComponent and only set the hours as you want.

So, could you try to do this :

let content = UNMutableNotificationContent()
content.title = "Do your daily review"
content.badge = 1

var triggerTime = DateComponents()
triggerTime.hour = 7

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

let request = UNNotificationRequest(identifier: "dailyNotification", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

I did it from my own side and it works.

I hope it may help.

My original code works fine, I just needed to do my testing differently. For some reason, if I set the time in my code to 7:00AM and then simulate that time on my Mac, it doesn't work, but if the time that I set it to is the real time of the day + 1 min, and I wait a real minute without changing my computer's time, it works. Perhaps Apple stops notifications that come soon after the time jumps to stop people from having notification troubles when they change timezones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM