【问题标题】:Repeating local notification is triggered immediately -- how to defer?立即触发重复本地通知——如何推迟?
【发布时间】:2017-01-20 16:35:27
【问题描述】:

我的目标是第一次设置一个在未来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])
}

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

谢谢!

【问题讨论】:

  • 这可能是一个错误。我以前看过这个问题。
  • 这是一个想法。尝试更大的间隔,例如 600。它现在会立即触发吗?
  • @matt 它仍然以非常大的间隔触发
  • 另一个想法:你是在设备上测试吗?
  • 不,在模拟器上。我将在几周后尝试在设备上进行测试,但您认为这可能与我看到的问题有什么关系?

标签: ios swift notifications ios10


【解决方案1】:

问题可能是您没有在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

【讨论】:

  • 我尝试设置标题 - 似乎没有任何影响。似乎也没有发生错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
相关资源
最近更新 更多