如何实施计划的本地通知

时间:2019-09-12 07:54:17

标签: ios swift notifications local localnotification

我在下面使用此代码来测试本地通知每小时的工作方式。但是我什么也没得到。

还可以在不同时间发送不同的本地通知消息吗?我只是在viewDidLoad()中调用LocalNotificationHour()

我刚刚开始学习快速,所以对不起。

-

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

2 个答案:

答案 0 :(得分:1)

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

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)

        }
    }

答案 1 :(得分:1)

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)