如何每次设置包含不同内容的重复日常通知?

问题描述 投票:1回答:1

我正在开发一款应用程序,可以在中午为您提供通知。这个通知每天应该是不同的。

我收到通知自己工作:

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() - 函数被调用,它返回一个字符串,并设置一个重复通知,它确实出现了指定的时间,但始终具有相同的内容。

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

ios swift uilocalnotification
1个回答
3
投票

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

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

您必须有一个类来处理其委托方法,可以是您的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)
                }
            }
        }
    }
}

这个答案也可以帮到你

Getting local notifications to show while app is in foreground Swift 3

© www.soinside.com 2019 - 2024. All rights reserved.