我正在开发一款可以在中午向您发送通知的应用程序。这个通知应该每天都不同。
我得到了通知本身的工作:
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 https://stackoverflow.com/questions/39713605/getting-local-notifications-to-show-while-app-is-in-foreground-swift-3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)