3
我用來在領域數據庫中插入遠程通知數據。但問題是,我發送每個通知content-available = 1
,這意味着每次通知進入didReceiveRemoteNotifications工作和無聲的通知是保存當用戶點擊或不通知。所以,如果我的應用程序在後臺,會有兩個插入的記錄。如何保護領域中的重複記錄插入
第一個條件是當通知進入應用程序後臺時,由於content-available = 1
而調用didReceiveRemoteNotification
並插入一條記錄。
所以,第二個條件是如果用戶點擊了通知中心內的通知,該方法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!)
}
}
}
這是我的境界對象
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 []
// }
}
那麼,有沒有什麼辦法來保護,在境界重複記錄插入之前,我插入一個新的記錄。我是新來的領域swift.Any幫助?
如果這不是一個答案,請給我留言 –
只是編輯我的答案 – desmond0321
仍然不清楚該怎麼辦,請您具體描述一下嗎? –