【问题标题】:UNNotificationRequest to send local notification daily at a specific timeUNNotificationRequest 每天在特定时间发送本地通知
【发布时间】:2020-10-06 14:29:49
【问题描述】:

由于 UILocalNotification 在 iOS10 中已被弃用,我无法理解如何将以下代码更新到 UNNotificationRequest 框架。我基本上让用户在他们选择的时间安排每日通知。例如,如果他们想在每天上午 11:00 收到通知。以下代码适用于 iOS10 以下的 iOS 版本,但由于 UILocalNotification 已弃用,因此不再有效。非常感谢任何帮助。

    let notification = UILocalNotification()
    notification.fireDate = fixedNotificationDate(datePicker.date)
    notification.alertBody = "Your daily alert is ready for you!"
    notification.timeZone = TimeZone.current
    notification.repeatInterval = NSCalendar.Unit.day
    notification.applicationIconBadgeNumber = 1
    UIApplication.shared.scheduleLocalNotification(notification)

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以使用UNCalendarNotificationTrigger 创建一个使用UNUserNotificationCenter 重复触发的通知。你可以做这样的事情。诀窍是在触发日期中只包含时间组件。

            let center = UNUserNotificationCenter.current()
    
            let content = UNMutableNotificationContent()
            content.title = "Attention!"
            content.body = "Your daily alert is ready for you!"
            content.sound = UNNotificationSound.default
    
            let identifier = "com.yourdomain.notificationIdentifier"
    
            var triggerDate = DateComponents()
            triggerDate.hour = 18
            triggerDate.minute = 30
            let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
    
            let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    
            center.add(request, withCompletionHandler: { (error) in
                if let error = error {
                    // Something went wrong
                    print("Error : \(error.localizedDescription)")
                } else {
                    // Something went right
                    print("Success")
                }
            })
    

    【讨论】:

      【解决方案2】:

      您无法安排每天重复的通知。该通知只会发生一次,然后您必须重新安排它,这意味着您必须再次打开应用程序。

      iOS 13 中引入了 BGTask API,可以用来执行一些后台任务,但不是这个,你不能将任务安排到特定的时间。这个 API 最后只在以下情况下有效应用程序在后台,而不是在它被杀死时。您只能设置一些时间间隔,系统将用作指导点来确定何时执行您的应用程序代码。但根据我的经验,它非常不可靠。

      实现这一点的唯一方法是实现远程推送通知。即使应用程序被终止,推送通知也可以工作。

      【讨论】:

        猜你喜欢
        • 2018-09-26
        • 2023-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多