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

时间:2017-01-20 16:35:27

标签: ios swift notifications ios10

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

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

App代表:

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])
}

我可以通过创建非重复通知然后在过期时开始重复通知来解决此问题。但是,我希望有一些方法来指定第一个触发日期 - 如果内存服务正确,旧的通知API具有这种能力,也许我误解了这个新的API

谢谢!

1 个答案:

答案 0 :(得分:0)

问题可能是您没有在UNMutableNotificationContent()上设置标题。

content.title = "Title goes Here"

此外,要查看添加请求是否有错误,您可以添加以下代码。

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

我是从Apple的文档中得到的 - https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent