我曾经在领域数据库中插入远程通知数据。但问题是,
我发送的每个通知都带有AVAudioPlayer
,这意味着每次通知都会在didReceiveRemoteNotifications中发布,当用户点击或不通知时,保存静默通知。因此,如果我的应用程序在后台,则会有两次记录插入。
第一个条件是当应用程序处于后台时发出通知,content-available = 1
因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!)
}
}
}
那么,在插入新记录之前,有什么方法可以保护域中的重复记录插入。我是realm swift的新手。有什么帮助吗?
答案 0 :(得分:8)
您的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
存在,它将更新数据。