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?