【问题标题】:How can I make UNNotificationRequest pop immediately?如何让 UNNotificationRequest 立即弹出?
【发布时间】:2017-09-24 00:34:16
【问题描述】:

我正在使用UNNotificationRequest,我希望在单击按钮时立即弹出通知。但在这种情况下,它会在我退出应用程序时出现。 这是我的代码

@IBAction func shortNotifBtn(_ sender: Any) {
    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    content.title = "Late wake up call"
    content.body = "The early bird catches the worm, but the second mouse gets the cheese."
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}

【问题讨论】:

  • 你必须实现一些方法...见here
  • 谢谢问题解决了:)

标签: ios swift notifications ios10 unnotificationrequest


【解决方案1】:

当问题涉及更现代的UNNotificationRequest 时,Max 的答案是针对已弃用的UILocalNotification

正确答案是传递nil。根据documentation for UNNotificationRequest's requestWithIdentifier:content:trigger:

trigger

导致发送通知的条件。 指定 nil 以立即发送通知。

所以在你的代码中:

let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)

【讨论】:

  • trigger:nil 为我工作。测试IOS 12.2,Iphone 6S Plus。
  • 在 iOS13 上为我工作。
  • 不知何故,我在执行此操作时看到通知显示前大约有 5 秒钟的延迟,并且还没有弄清楚它可能是什么。
  • 将此作为单独的问题发布,我将尝试研究可能导致此问题的原因@kwl
【解决方案2】:

https://developer.apple.com/reference/uikit/uilocalnotification

如果在系统传递通知时应用程序处于最前面且可见,则调用应用程序委托的 application(_:didReceive:) 来处理通知。使用提供的 UILocalNotification 对象中的信息来决定要采取的操作。当应用程序已经位于最前面时,系统不会显示任何警报、标记应用程序的图标或播放任何声音。

这是正常行为。除了为什么你需要通过点击按钮来触发本地通知?为什么不在点击按钮而不是通过通知时实现所需的功能?

【讨论】:

  • 这是一个测试,我只想在单击按钮时显示通知。
猜你喜欢
  • 2021-08-22
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2015-01-23
  • 1970-01-01
相关资源
最近更新 更多