我曾经在领域数据库中插入远程通知数据。但是,问题是,我发送每条通知,content-available = 1
这意味着每当通知进入didReceiveRemoteNotifications工作时,当用户单击或不单击通知时,静默通知就会保存。因此,如果我的应用程序在后台,将插入两个记录。
第一个条件是当通知到达应用程序在后台的位置时,由于didReceiveRemoteNotification
被调用content-available = 1
并插入一条记录。
因此,第二个条件是,如果用户在通知中心内点击通知,该方法将didReceiveRemoteNotification
再次起作用并插入相同的记录。因此,存在重复问题。
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
if let aps = userInfo["aps"] as? NSDictionary{
if let alert = aps["alert"] as? NSDictionary{
if let mbody = alert["body"] as? String{
print("Message Body : \(body)")
body = mbody
}
if let mtitle = alert["title"] as? String{
print("Message Title : \(title)")
title = mtitle
}
}
}
let newNotification = NotificationList()
newNotification.title = title
newNotification.body = body
oneSignalHelper.insertOneSignalNotification(newNotification)
NSNotificationCenter.defaultCenter().postNotificationName("refreshNotification", object: nil)
handler(UIBackgroundFetchResult.NewData)
}
这是我的领域代码
func insertOneSignalNotification(list: NotificationList){
// Insert the new list object
try! realm.write {
realm.add(list)
}
// Iterate through all list objects, and delete the earliest ones
// until the number of objects is back to 50
let sortedLists = realm.objects(NotificationList).sorted("createdAt")
while sortedLists.count > totalMessage {
let first = sortedLists.first
try! realm.write {
realm.delete(first!)
}
}
}
这是我的境界对象
import RealmSwift
class NotificationList: Object {
dynamic var title = ""
dynamic var body = ""
dynamic var createdAt = NSDate()
let notifications = List<Notification>()
// Specify properties to ignore (Realm won't persist these)
// override static func ignoredProperties() -> [String] {
// return []
// }
}
因此,在我插入新记录之前,有什么方法可以保护在域中重复记录的插入。我是Swift领域的新手。有帮助吗?
您NotificationList
需要一个主键。
将主键设置为对象,如下所示:
class NotificationList: Object {
dynamic var title = ""
dynamic var body = ""
dynamic var createdAt = NSDate()
dynamic var id = 0
let notifications = List<Notification>()
override static func primaryKey() -> String? {
return "id"
}
}
然后使用添加对象add(_:update:)
:
realm.add(newNotification, update: true)
如果id
存在,它将更新数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句