【问题标题】:handling local push notifications when app is in the background当应用程序在后台时处理本地推送通知
【发布时间】:2017-05-15 22:18:34
【问题描述】:

在 iOS 10 中,我看到有两个处理本地推送通知的函数:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)

第一个在应用程序处于前台时发生推送通知时调用。第二种情况发生在应用程序在后台并且用户单击通知时发生推送通知。

我的问题是,有没有办法在应用程序处于后台时处理本地推送通知而无需用户单击它?理想情况下,我希望我的所有推送通知,无论是在应用程序处于后台还是前台时,都可以触发 CloudKit 更新。这甚至可能吗?

谢谢!

【问题讨论】:

  • 如果你使用 CloudKit 那么你可以使用didReceiveRemoteNotification:completionHandler App 委托方法
  • 好吧,我实际上并没有使用远程通知。我希望我的 local 通知触发一个对数据库执行 add 操作的函数。
  • iOS 上没有基于时间安排的后台执行模式。

标签: ios swift push-notification apple-push-notifications


【解决方案1】:

我能想到的唯一方法是向您的应用添加通知扩展。有两种类型:“通知服务扩展”和“通知内容扩展”。

两者最初都是为了其他东西,但是两者都可以在这种情况下工作,因为它们都可以实现方法didReceive(_:withContentHandler:),如果应用程序在后台,则由扩展来接收和响应通知。

我建议使用“Notification Service Extension”(它最初是为了在显示通知内容之前更改它的内容,但您可以不修改它),并实现didReceive(_:withContentHandler:) 方法。只需使用相同的原始通知调用内容处理程序并触发 CloudKit 更新。

这是一个关于如何添加服务扩展的好教程:https://code.tutsplus.com/tutorials/ios-10-notification-service-extensions--cms-27550

在其“3. 扩展代码”部分中,有一个如何实现该方法的示例,并带有注释“// Edit properties of copy”,这正是我将添加代码以触发 CloudKit 更新的地方,因此它被执行每当应用程序在后台显示通知之前。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
相关资源
最近更新 更多