Thi*_*ung 6 realm apple-push-notifications ios swift
我曾经在领域数据库中插入远程通知数据.但是,问题是,我发送的每个通知content-available = 1都意味着每次通知都来自didReceiveRemoteNotifications工作,并且当用户点击或不通知时保存静默通知.所以,如果我的应用程序在后台,将有两个记录插入.
第一个条件是当应用程序处于后台时发出通知,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)
}
Run Code Online (Sandbox Code Playgroud)
这是我的领域代码
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!)
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的领域对象
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 []
// }
}
Run Code Online (Sandbox Code Playgroud)
那么,在我插入新记录之前,有没有办法在领域保护重复记录插入.我是realm swift的新手.有什么帮助吗?
小智 10
你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"
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用add(_:update:)以下命令添加对象
realm.add(newNotification, update: true)
Run Code Online (Sandbox Code Playgroud)
如果id存在,它将更新数据.
| 归档时间: |
|
| 查看次数: |
2182 次 |
| 最近记录: |