如何使用 couchbase 在 Swift 4 中通过数据库观察器检索数据?
How to retrive data through database observer in Swift4 with couchbase?
我是 Couchbase 和 Nosql 的新手。我可以在 CouchBase DB 上上传数据并通过枚举器检索它们并在 table 视图中显示它们。但是我想通过可以观察数据库变化的观察者检索数据,我可以立即将这些数据从 Couchbase 数据库保存在我的本地数据库中。我在 Swift4 Xcode9.1。谁能帮帮我???
尝试在获取数据时使用下面的方法,以便它检测数据库中的变化。
创建一个函数如下:
fileprivate func addLiveQueryObserverAndStartObserving() {
guard let liveQuery = liveQuery else {
return
}
// 1. iOS Specific. Add observer to the live Query object
liveQuery.addObserver(self, forKeyPath: "rows", options: NSKeyValueObservingOptions.new, context: nil)
// 2. Start observing changes
liveQuery.start()
}
也参考这个starterkit
通过下面的数据库变化可以在Swift4中观察到
NotificationCenter.default.addObserver(forName: NSNotification.Name.cblDatabaseChange, object: database, queue: nil) {
(notification) -> Void in
if let changes = notification.userInfo!["changes"] as? [CBLDatabaseChange] {
for change in changes {
NSLog("Document '%@' changed.", change.documentID)
let document = self.database.document(withID: change.documentID)
var properties = document?.properties
if let id = properties?["id"] as? String, let name = properties?["name"] as? String, let age = properties?["age"] as? String {
self.person.uniqueIDs = Int(id)
print(self.person.uniqueIDs ?? "i")
self.person.names = name
print(self.person.names ?? "n")
self.person.ages = Int(age)
print(self.person.ages ?? "a")
self.core.savedObjects(id: Int(self.person.uniqueIDs), name: String(self.person.names), age: Int(self.person.ages))
}
}
}
}
我是 Couchbase 和 Nosql 的新手。我可以在 CouchBase DB 上上传数据并通过枚举器检索它们并在 table 视图中显示它们。但是我想通过可以观察数据库变化的观察者检索数据,我可以立即将这些数据从 Couchbase 数据库保存在我的本地数据库中。我在 Swift4 Xcode9.1。谁能帮帮我???
尝试在获取数据时使用下面的方法,以便它检测数据库中的变化。
创建一个函数如下:
fileprivate func addLiveQueryObserverAndStartObserving() {
guard let liveQuery = liveQuery else {
return
}
// 1. iOS Specific. Add observer to the live Query object
liveQuery.addObserver(self, forKeyPath: "rows", options: NSKeyValueObservingOptions.new, context: nil)
// 2. Start observing changes
liveQuery.start()
}
也参考这个starterkit
通过下面的数据库变化可以在Swift4中观察到
NotificationCenter.default.addObserver(forName: NSNotification.Name.cblDatabaseChange, object: database, queue: nil) {
(notification) -> Void in
if let changes = notification.userInfo!["changes"] as? [CBLDatabaseChange] {
for change in changes {
NSLog("Document '%@' changed.", change.documentID)
let document = self.database.document(withID: change.documentID)
var properties = document?.properties
if let id = properties?["id"] as? String, let name = properties?["name"] as? String, let age = properties?["age"] as? String {
self.person.uniqueIDs = Int(id)
print(self.person.uniqueIDs ?? "i")
self.person.names = name
print(self.person.names ?? "n")
self.person.ages = Int(age)
print(self.person.ages ?? "a")
self.core.savedObjects(id: Int(self.person.uniqueIDs), name: String(self.person.names), age: Int(self.person.ages))
}
}
}
}