立即触发重复本地通知——如何推迟?

Vas*_*kov 5 notifications ios swift ios10

我的目标是设置一个将在未来 N 秒内第一次发生的通知,然后每 N 秒重复一次。

但是,创建重复通知似乎会UNUserNotificationCenterDelegate立即触发。

应用程序委托:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    return true
}

func startRequest() {
    let content = UNMutableNotificationContent()
    content.body = bodyText
    content.categoryIdentifier = categoryIdentifier
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
    trigger.nextTriggerDate()
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request)
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // This callback received right after the request is made
    completionHandler([.alert, .sound])
}
Run Code Online (Sandbox Code Playgroud)

我可以通过创建一个非重复通知,然后在它到期时开始重复通知来解决这个问题。但是,我希望有某种方法可以指定第一个触发日期——如果没记错的话,旧的通知 API 有这种能力,也许我误解了这个新 API

谢谢!

小智 0

问题可能是您没有在UNMutableNotificationContent().

content.title = "Title goes Here"
Run Code Online (Sandbox Code Playgroud)

另外,要查看添加请求是否出错,可以添加以下代码。

center.add(request) { (error : Error?) in
   if let theError = error {
     // Handle any errors
   }
}
Run Code Online (Sandbox Code Playgroud)

我从苹果的文档中得到了这个 - https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent