【问题标题】:How to implement scheduled local notification如何实现预定的本地通知
【发布时间】:2019-09-12 07:54:17
【问题描述】:

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

另外,有没有办法在不同的时间发送不同的本地通知消息?我只是在 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")}
}

【问题讨论】:

    标签: ios swift notifications local localnotification


    【解决方案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)
    

    【讨论】:

    • 所有与调度通知相关的代码都应该移动到requestAuthorization回调并在添加请求之前检查权限授予标志。
    • 非常感谢。这对理解很有帮助
    【解决方案2】:

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

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

    【讨论】:

    • 所以每 60 秒重复一次通知。如果我想要一个小时,我应该放3600?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    相关资源
    最近更新 更多