在 ios 中接收推送通知时后台执行不起作用
Posted
技术标签:
【中文标题】在 ios 中接收推送通知时后台执行不起作用【英文标题】:background execution is not working when receive push notification in ios 【发布时间】:2020-01-09 07:42:11 【问题描述】:当应用程序收到推送通知时,我正在尝试将数据转换为核心数据,当应用程序使用以下方法处于前台时,这可以正常工作
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
if let userInfo = notification.request.content.userInfo as? [String : Any]
let aps = userInfo["aps"] as? NSDictionary
let alert = aps?["alert"] as? NSDictionary
let context = self.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "NotificationDetails", in: context)
let NotificationDetail = NSManagedObject(entity: entity!, insertInto: context)
NotificationDetail.setValue( incidentDetails.incidentNumber, forKey: "Number")
do
try context.save()
catch
print("Failed saving")
但是当应用程序不工作时,我使用下面的方法,它没有保存,
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
if let userInfo = notification.request.content.userInfo as? [String : Any]
let aps = userInfo["aps"] as? NSDictionary
let alert = aps?["alert"] as? NSDictionary
let context = self.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "NotificationDetails", in: context)
let NotificationDetail = NSManagedObject(entity: entity!, insertInto: context)
NotificationDetail.setValue( incidentDetails.incidentNumber, forKey: "Number")
do
try context.save()
catch
print("Failed saving")
completionHandler(.newData)
应用不工作时如何保存数据?
【问题讨论】:
您可以实现静默推送通知,但它有一些限制。你需要更多地去探索它是否有用 检查你检查这个方法是否被调用 - private func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) 【参考方案1】:您必须确保您的通知负载具有 "content-available":1;类似:
"aps" :
"content-available" : 1
,
"acme1" : "bar",
"acme2" : 42
然后,你会得到一个回调:
application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
【讨论】:
请通过这个:developer.apple.com/documentation/usernotifications/… 我已经启用了该功能,但仍然无法正常工作我得到如下所示这是正确的吗? alert = body = "消息正文";标题=“标题”; ; “内容可用”= 1; “可变内容”= 1; ]以上是关于在 ios 中接收推送通知时后台执行不起作用的主要内容,如果未能解决你的问题,请参考以下文章