我曾经在领域数据库中插入远程通知数据.但是,问题是,我发送的每个通知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() // Specify properties to ignore (Realm won't persist these) // override static func ignoredProperties() -> [String] { // return [] // } }
那么,在我插入新记录之前,有没有办法在领域保护重复记录插入.我是realm swift的新手.有什么帮助吗?
你NotificationList
需要一把钥匙.
将主键设置为您的对象,如下所示:
class NotificationList: Object { dynamic var title = "" dynamic var body = "" dynamic var createdAt = NSDate() dynamic var id = 0 let notifications = List() override static func primaryKey() -> String? { return "id" } }
然后使用add(_:update:)
以下命令添加对象
realm.add(newNotification, update: true)
如果id
存在,它将更新数据.