Update Firebase local data with observeSingleEvent - ios

so I have a function to retrieve the user information from a given user id:
func getUserDataFrom(_ userID: String, completion: #escaping (_ userData: DBUser) -> Void) {
ref.child(usersTable).child(userID).observeSingleEvent(of: .value) { (snapshot) in
if let userDic = snapshot.value as? NSDictionary {
let userData = DBUser(with: userDic)
completion(userData)
}
}
}
The problem is that this returns the local data instead of reading from Firebase. I'd like to retrieve the data from the server (as long as there's internet connection) and only read from disk if it's not available.
I know that the easiest way to accomplish this would be using a listener, but I'm making a Today Extension and they use way too much memory increasing the chances of a crash.
I've also researched about keepSynced feature but since the database reference to the users table will have a lot of children I don't know if this will affect the memory of my extension.
Long story short: I'd like to read data from Firebase once, and only read from disk if there isn't internet connection with the minimum memory usage possible.
Thank you in advance.

I retrieve some explanation, I think it might help you in your case :
ObserveSingleEventType with keepSycned will not work if the Firebase
connection cannot be established on time. This is especially true
during appLaunch or in the appDelegate where there is a delay in the
Firebase connection and the cached result is given instead. It will
also not work at times if persistence is enabled and
observeSingleEvent might give the cached data first. In situations
like these, a continuous ObserveEventType is preferred and should be
used if you absolutely need fresh data.
I think you don't have the choice to use a continuous listener. But to avoid performance issues why you don't remove yourself your listeners when you don't it anymore.

In the fresh project I created and added your code, it retrieves data from Firebase when there's a connection and when not, from local storage. Because of that, we conclude the above code is correctly fetching Firebase data from their server.
However, in my experience observeSingleEvent and offline persistence has been a tad intermittent (perhaps a 'feature'?). To fix it, force the data at the reference to stay sync'd
let usersTableRef = Database.database().reference(withPath: usersTable)
let thisUsersTableRef = usersTableRef.child(userId)
thisUsersTableRef.keepSynced(true)
//optional: thisUsersTableRef.child("temp").setValue(true)
thisUsersTableRef.observeSingleEvent(of: .value)
See Offline Capabilities for a bit more info and further examples.
Also see this post from 2015 for some insight on observers/listeners.

Related

How to handle first time launch experience when iCloud is required?

I am using CloudKit to store publicly available data and the new NSPersistentCloudKitContainer as part of my Core Data stack to store/sync private data.
When a user opens my app, they are in 1 of 4 states:
They are a new user with access to iCloud
They are a returning user with access to iCloud
They are a new user but do not have access to iCloud for some reason
They are a returning user but do not have access to iCloud for some reason
States 1 and 2 represent my happy paths. If they are a new user, I'd like to seed the user's private store with some data before showing the initial view. If they are a returning user, I'd like to fetch data from Core Data to pass to the initial view.
Determining new/old user:
My plan is to use NSUbiquitousKeyValueStore. My concern with this is handling the case where they:
download the app -> are recorded as having launched the app before -> delete and reinstall/install the app on a new device
I assume NSUbiquitousKeyValueStore will take some time to receive updates so I need to wait until it has finished synchronizing before moving onto the initial view. Then there's the question of what happens if they don't have access to iCloud? How can NSUbiquitousKeyValueStore tell me if they are a returning user if it can't receive the updates?
Determining iCloud access:
Based on the research I've done, I can check if FileManager.default.ubiquityIdentityToken is nil to see if iCloud is available, but this will not tell me why. I would have to use CKContainer.default().accountStatus to learn why iCloud is not available. The issue is that is an asynchronous call and my app would have moved on before learning what their account status is.
I'm really scratching my head on this one. What is the best way to gracefully make sure all of these states are handled?
There's no "correct" answer here, but I don't see NSUbiquitiousKeyValueStore being a win in any way - like you said if they're not logged into iCloud or don't have network access it's not going to work for them anyway. I've got some sharing related stuff done using NSUbiquitiousKeyValueStore currently and wouldn't do it that way next time. I'm really hoping NSPersistentCloudKitContainer supports sharing in iOS 14 and I can just wipe out most of my CloudKit code in one fell swoop.
If your app isn't functional without cloud access then you can probably just put up a screen saying that, although in general that's not a very satisfying user experience. The way I do it is to think of the iCloud sync as truly asynchronous (which it is). So I allow the user to start using the app. Then you can make your call to accountStatus to see if it's available in the background. If it is, start a sync, if it's not, then wait until it is and then start the process.
So the user can use the app indefinitely standalone on the device, and at such time as they connect to the internet everything they've done on any other device gets merged into what they've done on this new device.
I struggled with this problem as well just recently. The solution I came up with was to query iCloud directly with CloudKit and see if it has been initialized. It's actually very simple:
public func checkRemoteData(completion: #escaping (Bool) -> ()) {
let db = CKContainer.default().privateCloudDatabase
let predicate = NSPredicate(format: "CD_entityName = 'Root'")
let query = CKQuery(recordType: .init("CD_Container"), predicate: predicate)
db.perform(query, inZoneWith: nil) { result, error in
if error == nil {
if let records = result, !records.isEmpty {
completion(true)
} else {
completion(false)
}
} else {
print(error as Any)
completion(false)
}
}
}
This code illustrates a more complex case, where you have instances of a Container entity with a derived model, in this case called Root. I had something similar, and could use the existence of a root as proof that the data had been set up.
See here for first hand documentation on how Core Data information is brought over to iCloud: https://developer.apple.com/documentation/coredata/mirroring_a_core_data_store_with_cloudkit/reading_cloudkit_records_for_core_data
to improve whistler's solution on point 3 and 4,
They are a new user but do not have access to iCloud for some reason
They are a returning user but do not have access to iCloud for some reason
one should use UserDefaults as well, so that it covers offline users and to have better performance by skipping network connections when not needed, which is every time after the first time.
solution
func isFirstTimeUser() async -> Bool {
if UserDefaults.shared.bool(forKey: "hasSeenTutorial") { return false }
let db = CKContainer.default().privateCloudDatabase
let predicate = NSPredicate(format: "CD_entityName = 'Item'")
let query = CKQuery(recordType: "CD_Container", predicate: predicate)
do {
let items = (try await db.records(matching: query)).matchResults
return items.isEmpty
} catch {
return false
// this is for the answer's simplicity,
// but obviously you should handle errors accordingly.
}
}
func showTutorial() {
print("showing tutorial")
UserDefaults.shared.set(true, forKey: "hasSeenTutorial")
}
As it shows, after the first time user task showTutorial(), UserDefaults's bool value for key "hasSeenTutorial" is set to true, so no more calling expensive CK... after.
usage
if await isFirstTimeUser() {
showTutorial()
}

Firebase observe by value fetches old value from cached data

I have been facing some issues with firebase persistence once enabled, I had a chance to read through the rest of posted questions and reviewed there answers but still haven't got things to work as expected.
I have enabled firebase persistence and using observe by value to fetch recent update of particular node. Not only it keeps fetching old values but also once I leave a particular view controller and go back to that view controller the value changes to recent one.
Is there a proper way to request for recent value at first call?
Code I have tried:
// MARK: Bill authenticate function
func authenticateBill(completion: #escaping (_ bill: Double?, _ billStatus: BillError?) -> Void) {
// Observe incase bill details exist for current case
let billRef = self.ref.child("bills").child((caseRef?.getCaseId())!)
billRef.observe(FIRDataEventType.value, with: { (billSnapshot) in
if !billSnapshot.exists() {
completion(nil, BillError.unavailable)
return
}
if let billDictionary = billSnapshot.value as? [String: AnyObject] {
let cost = billDictionary["cost"] as! Double
print("Cost: ", cost)
completion(cost, nil)
}
})
}
No, with persistence enabled, your first callback will contain the immediately-available value from the cache (if any), followed by updates from the server (if any). You can't indicate to the SDK that you want either cached or fresh data.
If you want to keep a particular location up to date all the time while persistence is enabled, you can use keepSynced to indicate to the SDK it should always be listening and caching the data at that location. That comes at an indeterminate cost in bandwidth, depending on how frequently the data changes.
You can use the REST API to request fresh data without going through any caching mechanisms.

What's the right way to do an initial load of list data in Firebase and Swift?

Every firebase client example I see in Swift seems to oversimplify properly loading data from Firebase, and I've now looked through all the docs and a ton of code. I do admit that my application may be a bit of an edge case.
I have a situation where every time a view controller is loaded, I want to auto-post a message to the room "hey im here!" and additionally load what's on the server by a typical observation call.
I would think the flow would be:
1. View controller loads
2. Auto-post to room
3. Observe childAdded
Obviously the calls are asynchronous so there's no guarantee the order of things happening. I tried to simplify things by using a complete handler to wait for the autopost to come back but that loads the auto-posted message twice into my tableview.
AutoPoster.sayHi(self.host) { (error) in
let messageQuery = self.messageRef.queryLimited(toLast:25).queryOrdered(byChild: "sentAt")
self.newMessageRefHandle = messageQuery.observe(.childAdded, with: { (snapshot) in
if let dict = snapshot.value as? [String: AnyObject] {
DispatchQueue.main.async {
let m = Message(dict, key: snapshot.key)
if m.mediaType == "text" {
self.messages.append(m)
}
self.collectionView.reloadData()
}
}
})
}
Worth noting that this seems very inefficient for an initial load. I fixed that by using a trick with a timer that will basically only allow the collection view to reload maximum every .25s and will restart the timer every time new data comes in. A bit hacky but I guess the benefits of firebase justify the hack.
I've also tried to observe the value event once for an initial load and then only after that observe childAdded but I think that has issues as well since childAdded is called regardless.
While I'm tempted to post code for all of the loading methods I have tried (and happy to update the question with it), I'd rather not debug what seems to not be working and instead have someone help outline the recommended flow for a situation like this. Again, the goal is simply to auto-post to the room that I joined in the conversation, then load the initial data (my auto-post should be the most recent message), and then listen for incoming new messages.
Instead of
self.newMessageRefHandle = messageQuery.observe(.childAdded, with: { (snapshot) in
try replacing with
let childref = FIRDatabase.database().reference().child("ChildName")
childref.queryOrdered(byChild:"subChildName").observe(.value, with: { snapshot in

keepSynced(true) doesn't fetch the data for the location immediately

As the title mentioned, I get local data with keepSynced(true) and have to go out and back into the view to get the latest (fresh) data.
i have the following setup:
var baseRef: FIRDatabaseReference!
in viewDidLoad:
baseRef = FIRDatabase.database().reference()
baseRef.child("Posts").keepSynced(true)
then in viewWillAppear:
baseRef.child("Posts").queryOrderedByChild("sortTimestamp").observeSingleEventOfType(.Value, withBlock: { snapshot in //etc
I get local data, according to this post the data should be fresh as I keepSynced before I attach an observer:
https://groups.google.com/forum/#!searchin/firebase-talk/keepSynced/firebase-talk/SK9WVZvkHsU/HVjxtnv5JoYJ
"keepSynced will work fine both with disk persistence enabled and with it disabled. It immediately fetches the data for the location/query where you enable it, before you attach a listener"
However, as mentioned, I have to trigger this again, by going out and in of the viewController(almost like a refresh), to get fresh data
I did try the normal observeEventType(.Value as well as .ChildAdded, but with the pagination system I use observeSingleEventOfType works better except for the issues above
Not sure what I am missing, any suggestions are much appreciated.

Firebase started in offline mode, wont fire osberve* for child values

I'm using firebase with app started in offline mode, when i'm subscribing to child values of some node the callback from observe*(_:,withBlock:) is not firing (neither for initial values nor changes). Subscriptions to direct values (childless) works fine. Take a look at a snippet :
let database = FIRDatabase.database()
database.reference().keepSynced(true)
let databaseRef = database.reference()
database.goOffline()
databaseRef.child("user").setValue("user1")
let userKey = databaseRef.child("usr").childByAutoId().key
let userValues = ["uid": "uid",
"name" : "name",
"surname" : "surname"]
databaseRef.child("/usr/\(userKey)/").setValue(userValues)
//1
databaseRef.child("user").observeSingleEventOfType(.Value, withBlock:{ snap in
print("works")
})
//2
databaseRef.child("usr").observeSingleEventOfType(.Value, withBlock:{ snap in
print("doesnt work")
})
//3
databaseRef.child("usr/\(userKey)/uid").observeSingleEventOfType(.Value, withBlock:{ snap in
print("works")
})`
subscriptions 1 & 2 works fine, but subscribtion 2 won't fire, until at least once database go online. From the moment database syncronize with remote i can go offline and everything works as it should. Anyone know how to handle this issue?
When your app is offline, the Firebase client will fire events from its cache. If your app has never connected to the Firebase servers, this cache will be empty.
That means that the Firebase client has no knowledge on whether a value exists at the location you request. For that reason it will not fire an event.
I had a similar issue but I was using deep links with updateChildValues, which somehow caused the local cache to not fire events on intermediate (/path/intermediate/otherpath) keys. The workaround I found was to be more verbose in the dictionary I passed to updateChildValues. (I still believe this is a bug in the Firebase SDK).
See this Stack Overflow question

Resources