如何使用swift在应用程序关闭/后台时将推送通知保存到域
我使用后台使用如何使用swift在应用程序关闭/后台时将推送通知保存到域,swift,realm,firebase-cloud-messaging,apple-push-notifications,Swift,Realm,Firebase Cloud Messaging,Apple Push Notifications,我使用后台使用FCM将消息推送到iOS设备,我想存储推送信息(使用领域) 只有两种情况可以成功保存 1.应用程序运行 2.应用程序被终止/后台,并单击以推送横幅通知 我希望我可以在不点击横幅通知的情况下在后台运行应用程序并保存它 所以我用了下面的方法 在项目中添加通知服务扩展 启用后台提取/远程通知 已将项目和通知服务扩展添加到应用程序组 下一个问题出现了。我在unnotificationservice extension中使用了与AppDelegates相同的方法来存储推送代码,但它不起作用。
FCM
将消息推送到iOS
设备,我想存储推送信息(使用领域
)
只有两种情况可以成功保存
1.应用程序运行
2.应用程序被终止/后台,并单击以推送横幅通知
我希望我可以在不点击横幅通知的情况下在后台运行应用程序并保存它
所以我用了下面的方法
unnotificationservice extension
中使用了与AppDelegates
相同的方法来存储推送代码,但它不起作用。我看了一些相关的资料。似乎因为扩展不能共享领域数据库,我应该怎么做才能让他们共享数据
还是我的问题不在我的叙述中?请有经验的人来指导我,非常感谢,我的英语不好,如果我的问题不清楚,请让我知道
王国级
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"
}
}
class RealmDao: NSObject {
static let shared = RealmDao()
private var realm: Realm!
private override init() {
self.realm = try! Realm()
}
func getRealmObject() -> Realm {
return self.realm
}
}
类通知服务(NotificationService.swift)
AppDelegates.swift应用程序运行保存消息
let realm = try! Realm()
let order: Order = Order()
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])
}
这个问题对你来说还相关吗? 我认为您的问题是,任何扩展的RAM都受到某个内存值的限制(我知道的最后一个值是12MB)。当您尝试初始化领域时,iOS会从内存中卸载扩展,因为超出了限制 在我的例子中,我能够保存数据,有时不能,此时应用程序没有崩溃,只是结果没有实现。但是,如果我开始调试扩展并一步一步地完成所有初始化行,我会看到在用断点代替Realm init之后,调试模式被关闭,这表明超出了内存限制 为了避免这种情况,可以使用Realm.Configuration显式指定模式。当显式给出模式时,Realm不会调用objc_copyClassList(),因为不需要枚举所有类
let necessaryTypes = [SomeClass.self, AnotherClass.self]
let dataBaseURL = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: "yourIdentifier")!
.appendingPathComponent("default.realm")
let config = Realm.Configuration(fileURL: dataBaseURL, objectTypes: necessaryTypes)
let realm = try Realm(configuration: config)
let necessaryTypes = [SomeClass.self, AnotherClass.self]
let dataBaseURL = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: "yourIdentifier")!
.appendingPathComponent("default.realm")
let config = Realm.Configuration(fileURL: dataBaseURL, objectTypes: necessaryTypes)
let realm = try Realm(configuration: config)