How to protect duplicate record insertion in realm
Asked Answered
M

1

6

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?

Mcdaniels answered 17/12, 2015 at 7:30 Comment(0)
S
11

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.

Shive answered 17/12, 2015 at 7:41 Comment(3)
please leave me a comment if that is not an answerMcdaniels
still not clear what to do,can you please describe more specifically?Mcdaniels
hope this will help, and your Notification also need to add primary key as wellShive

© 2022 - 2024 — McMap. All rights reserved.