ios - 使用swift杀死应用程序时如何存储ios推送通知
问题描述
我使用自己的服务器,使用FCM推送通知到ios设备,推送成功,我也使用Realm数据库系统帮我存储fcm推送通知,但是只有以下两种情况才能存储成功。案例1:应用程序运行时。
案例2:当你点击推送banner通知时,应用程序被杀死,或者在后台运行。
但这不是我的主要意图。我知道当应用程序被杀死时,我无法处理推送通知,所以我希望能够在用户打开应用程序时存储推送通知。
对不起,我的英语不好。如果有不清楚的地方,请告诉我。
领域类
class Order: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var name = ""
@objc dynamic var amount = ""
@objc dynamic var createDate = Date()
override static func primaryKey() -> String? {
return "id"
}
let realm = try! Realm()
let order: Order = Order()
AppDelegate.swift(当应用运行存储 fcm 消息时)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo //
print("userInfo: \(userInfo)")
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
// handle any error here
return
}
print("Title: \(title) \nBody:\(body)")
order.name = title
order.amount = body
try! realm.write {
realm.add(order)
}
completionHandler([.badge, .sound, .alert])
}
单击以推送横幅通知 AppDelegate.swift(当应用程序终止或在后台单击以推送横幅通知)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print("userInfo: \(userInfo)")
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
// handle any error here
return
}
print("Title: \(title) \nBody:\(body)")
order.name = title
order.amount = body
try! realm.write {
realm.add(order)
}
completionHandler()
}
请有经验的人帮帮我,非常感谢。
解决方案
当您的应用程序被终止时,您可以将通知存储到您的数据库中。
- 将“通知服务扩展”添加到您的应用程序。
- 在您的应用中启用后台获取/远程通知功能。
- 在您的应用程序中启用“应用程序组”并使用您的“通知服务扩展”启用相同的功能。
- 现在您可以使用“应用程序组”访问您的数据库,并且可以在收到通知后立即将通知插入到您的数据库中。
要使用“App Group”访问数据库,请使用,
var fileMgr : FileManager!
let databasePathURL = fileMgr!.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>")
从上面的代码中,一旦您获得数据库的路径,您就可以对数据库执行插入操作。这将是您正在执行的正常插入操作。
在此文件和下图中突出显示的方法中插入用于保存数据的代码。
如果您需要任何其他帮助,请告诉我。
推荐阅读
- java - ClassLoader.getResources() 返回空枚举
- c# - C# 按实体类型自动创建存储库
- scala - 加特林 checkIf 语法
- python - 从 IP 地址获取子网
- azure-devops - VSTS 命名约定和标签的允许字符
- exception-handling - Symfony 4:kernel.exception 侦听器未捕获的异常,禁用调试
- reactjs - 有没有办法可以覆盖材料 UI 图标 npm 包在 React 中提供的颜色?
- c# - 具有泛型类型的 ObservableCollection 不起作用
- google-apps-script - 如何让 Google sheet Apps Script 为所有具有编辑权限的用户运行 onOpen 函数
- java - 当我导航回主页时,点击次数不会更新