如何设置每次具有不同内容的重复每日通知



我正在开发一个应用程序,可以在中午给你通知。此通知应该每天都不同。

我让通知本身正常工作:

let notificationOptions: UNAuthorizationOptions = [.alert, .sound];
UNUserNotificationCenter.current().requestAuthorization(options: notificationOptions) { (granted, error) in
    if !granted {
        print("Something went wrong")
    } else {
        let content = UNMutableNotificationContent()
        content.body = getRandomDailyString()
        content.sound = UNNotificationSound.default()
        let date = DateComponents(hour: 12, minute: 15)
        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
        let request = UNNotificationRequest(identifier: "Daily String", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print(error.localizedDescription)
            }
        }
    }
}

现在发生的事情是调用getRandomDailyString((-函数,它返回一个字符串,并设置一个重复通知,该通知确实出现在指定的时间,但始终具有相同的内容。

我将如何制作每天提供独特内容的通知?

现在无法测试,但请尝试并告诉我

如果它不在函数中,我会将其放在一个函数中。然后从委托方法调用它。不要忘记将其更改为不可重复。

您必须有一个类来处理其委托方法,可以是您的 AppDelegate 或您创建的任何其他类。

代表UNUserNotificationCenterDelegate

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    x()
}
func x() {
    let notificationOptions: UNAuthorizationOptions = [.alert, .sound];
    UNUserNotificationCenter.current().requestAuthorization(options: notificationOptions) { (granted, error) in
        if !granted {
            print("Something went wrong")
        } else {
            let content = UNMutableNotificationContent()
            content.body = getRandomDailyString()
            content.sound = UNNotificationSound.default()
            let date = DateComponents(hour: 12, minute: 15)
            let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
            let request = UNNotificationRequest(identifier: "Daily String", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request) { (error) in
                if let error = error {
                    print(error.localizedDescription)
                }
            }
        }
    }
}

这个答案也可以帮助你

获取要在应用程序处于前台时显示的本地通知 Swift 3

好的,这是解决方案。

不可能每天

安排随机内容的重复通知。内容是在计划通知时定义的,以后无法更改。

不过,您可以做的是提前安排多达 64 个通知。因此,您可以在接下来的 64 天内安排 64 个唯一通知,然后每当您打开应用程序时检查剩余的通知数量,并再次填写最多 64 个通知计划。

如果您在 64 天后未打开应用程序,则通知将停止发送:P

最新更新