如何保护领域中的重复记录插入

How to protect duplicate record insertion in realm

我曾经在领域 database.But 中插入远程通知数据,问题是, 我用 content-available = 1 发送每个通知,这意味着每次通知进入 didReceiveRemoteNotifications 时都会工作,并且当用户单击或不单击 notification.So 时保存静默通知,如果我的应用程序在后台,将插入两次记录。

第一个条件是当应用程序在后台收到通知时,由于 content-available = 1 而调用 didReceiveRemoteNotification 并插入一条记录。

所以,第二个条件是如果用户点击通知中心内的通知,该方法 didReceiveRemoteNotification 再次工作并插入相同的 record.So,重复问题。

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 []
//  }

}

那么,在我插入新的 record.I 领域新手之前,有什么方法可以保护领域中的重复记录插入 swift.Any 帮助?

您的 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 存在,它将更新数据。