我已经尝试了很多东西,但我似乎无法确定在(例如)2天或5小时内使用哪个命令来触发警报。谁能帮我吗?我希望能够做到的是:
var number = 3
var repeat = day
*Code with 'number' and 'repeat' in it.*
因此,在这种情况下,它会在3天内发出警报。这里有人知道怎么做吗? ^^
提前致谢!
答案 0 :(得分:3)
首先,将其放在需要通知的文件的顶部:
import UserNotifications
然后将其放在application(_:didFinishLaunchingWithOptions:)
AppDelegate
中
let notifCenter = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .badge, .sound]
notifCenter.requestAuthorization(options: options, completionHandler: nil)
现在请求通知如下:
// timeInterval is in seconds, so 60*60*12*3 = 3 days, set repeats to true if you want to repeat the trigger
let requestTrigger = UNTimeIntervalNotificationTrigger(timeInterval: (60*60*12*3), repeats: false)
let requestContent = UNMutableNotificationContent()
requestContent.title = "Title" // insert your title
requestContent.subtitle = "Subtitle" // insert your subtitle
requestContent.body = "A body in notification." // insert your body
requestContent.badge = 1 // the number that appears next to your app
requestContent.sound = UNNotificationSound.default()
// Request the notification
let request = UNNotificationRequest(identifier "PutANameForTheNotificationHere", content: requestContent, trigger: requestTrigger
// Post the notification!
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
// do something to the error
} else {
// posted successfully, do something like tell the user that notification was posted
}
这部分代码做了三件事:
如果您打算继续使用通知,请查看this tutorial,其中还介绍了当用户点按您的通知时如何做出反应。
注意:UNMutableNotificationContext
是可变的,尽管名称,UN
只是命名空间。不要混淆!
如果您提供副标题,则会在标题和正文之间。
这是badge
属性: