[英]How do I set up a repeating daily notification with different content each time?
我正在開發一款應用程序,可以在中午為您提供通知。 這個通知每天應該是不同的。
我收到通知自己工作:
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)
}
}
}
}
}
這個答案也可以幫到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.