如何实现定时本地通知

How to implement scheduled local notification

我在下面有这段代码来测试本地通知每小时是如何工作的。但是我什么也没得到。

另外,有没有办法在不同的时间发送不同的本地通知消息?我只是在 viewDidLoad()

中调用 LocalNotificationHour()

刚开始学习swift,在此先说声抱歉。

--

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

您可以通过添加以下代码安排每分钟的通知:

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)

        }
    }
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = 1
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

这基本上采用今天的日期并将时间设置为凌晨 1 点。使用:UNCalendarNotificationTrigger(dateMatching: 您告诉通知在今天凌晨 1 点触发,然后每天在同一时间重复。

要根据时间间隔触发通知,您应该使用 UNTimeIntervalNotificationTrigger

// Fire in 60 minutes (60 seconds times 60)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (60*60), repeats: false)