Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect duplicate record insertion in realm

I used to insert remote notification data inside realm database.But,the problem is, I send every notification with content-available = 1 which mean everytime the notifications comes in the didReceiveRemoteNotifications worked and silent notification is save when user click or not the notification.So,if my app in the background,there will be two insertions of record.

The first condition is when the notification comes in where the app is in background,the didReceiveRemoteNotification called because of content-available = 1 and insert one record.

So,the second condition is if the user tapped the notification inside notification center,that method didReceiveRemoteNotification work again and insert that same record.So,duplicate problem.

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)

}

Here is my realm code

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!)
        }    
    }
}

This is my realm object

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

}

So,is there any way to protect that duplicate record insertion at realm before i insert a new record.I am new to realm swift.Any help?

like image 763
Thiha Aung Avatar asked Dec 17 '15 07:12

Thiha Aung


1 Answers

Your NotificationList needs a primary key.

Set the primary key to your object like seen below:

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"
   }
}

Then add the object using add(_:update:):

realm.add(newNotification, update: true)

If the id exists, it will update the data.

like image 118
desmond0321 Avatar answered Oct 31 '22 08:10

desmond0321