Firebase data retrieval sporadically not returning - ios

I am building a project with Firebase that involves users. There is a known Firebase bug where even after a user has been deleted from the Firebase Authentication section, the user is still able to access the app and still has read/write permissions to the database. I believe it has something to do with the token being stored by Firebase on the user's device.
As a work around to this, I have implemented a "user checkup" where my app will check to see if the userID of the logged in user exists in my real-time database. This way all i have to do is delete the userID node from the real-time database and that will cause this checkup to fail and thus log the user out permanently.
The problem i am having is that the call to observeSingleEvent(of: .value...) is sporadically not returning. By this i mean that sometimes it returns immediately as is expected, however sometimes it just doesn't return at all. For example yesterday morning it wasn't working at all. Yesterday afternoon and night it worked fine. Now today it is no longer working again. Code below...
func checkDatabaseForFIRUser(withId: String, callback: #escaping (Bool)-> Void) {
let fireUsersRef = fireRootRef.child("all-users").child(withId)
fireUsersRef.observeSingleEvent(of: .value, with: {(snapshot)-> Void in
print("user check result -> \(snapshot)")
if snapshot.exists() {
print("SNAP EXISTS")
callback(true)
} else {
print("SNAP NOT EXISTS")
callback(false)
}
}, withCancel: {(error)-> Void in
print("CANCEL BLOCK ERROR = \(error) and localized description = \(error.localizedDescription)")
})
}
I have also noticed that during the times when I am unable to retrieve data I am also unable to write anything to the database, it is as if nothing at all works. My Firebase Rules have been set to "Public" so anyone can read/write. And I have a working internet connection on my device
EDIT: everything works fine on Simulator. Issue is only occurring on the actual device
EDIT #2: This issue seems to have subsided, I haven't noticed it for at least a few weeks now

I bet that by the time you are calling observeSingleEvent, you are log out, so probably that's why it is not returning anything.

Related

onDisconnectRemoveValue doesn't delete (key: value) after log out firebase?

I am using FBSDKLoginManager().logOut() and try! FIRAuth.auth()!.signOut() for log out account in Swift. But onDisconnectRemoveValue doesn't remove (key: true) from Firebase "online/key" child node. Should I remove this key manually or what's wrong with this case?
If you CMD+CLICK on onDisconnectRemoveValue you will be navigated to the firebase documentation , :-
Ensure the data at this location is removed when
the client is disconnected (due to closing the app, navigating to a new page, or network issues).
So when you log out the user the network link to firebase is still alive, you haven't closed your app yet and neither have you navigated to another app leaving your firebase app in background.
So, try using this:-
FIRDatabase.database().reference().child("your_Path").updateChildValues(["online" : false], withCompletionBlock: {(err, ref) in
if err == nil{
// Sign out your user
}
})

Firebase Query Error Handling

I've got some functions to read data from Firebase, but sometimes I never get a response (or it's massively delayed). I read here that maybe Firebase can close the socket connection before data is received. It looks like someone had a similar issue here, but never posted a solution.
Here's a sample of my code for downloading user data from Firebase.
// loads the current user's information
static func loadUserDataWithCompletion(completion: (UserInfo) -> Void) {
let ref = FIRDatabase.database().reference()
print("loading current user data...")
let uid = (FIRAuth.auth()?.currentUser?.uid)!
ref.child("users").queryOrderedByKey().queryEqualToValue(uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in
print("found user data!")
if let dictionary = snapshot.value as? [String:AnyObject] {
let info = userFromDict(dictionary)
// execute code slated for completion
completion(info)
}
})
}
Is there some way I can detect errors using observeEventType? Maybe then I'd at least get more information about why the issue is happening.
There can be three possible errors that you might face while observing your database :-
You haven't defined a proper path to your database observe query
You are parsing in a wrong or faulty manner
You don't have the permission to access that particular node at that particular time(Security Rules)
For the first two you have to take care of it yourself, But for the third condition you can use withCancel block:-
FIRDatabase.database().reference().child("users").queryOrderedByKey().queryEqual(toValue: "uid").observe(.childAdded, with: { (snapshot) in
//your code
}, withCancel: {(err) in
print(err) //The cancelBlock will be called if you will no longer receive new events due to no longer having permission.
})
As far as error handling if the user looses network connection while Writing, Your app remains responsive regardless of network latency or connectivity. See the Write data offline section of Firebase Docs

Apple Store build rejected while using CloudKit/iCloud

I just submited my app to the Apple Store and it failed submission because of the following issue and I am quite confuse about how to work around it.
From Apple - 17.2 Details - We noticed that your app requires users to
register with personal information to access non account-based
features. Apps cannot require user registration prior to allowing
access to app content and features that are not associated
specifically to the user.
Next Steps - User registration that requires the sharing of personal
information must be optional or tied to account-specific
functionality. Additionally, the requested information must be
relevant to the features.
My app uses CloudKit to save, retrieve and share records. But the app itself do not ask for any personal details neither share any personal details like emails, names, date of birth..., it just asks the user to have an iCloud account active on the device. Then CloudKit uses the iCloud credentials in order to work.
It becomes confusing because:
1 - I can't change the way CloudKit works and stop asking for the user to login on iCloud. Every app that uses CloudKit needs an user logged on iCloud.
2 - As other apps (facebookas an example) if you do not login the app cannot fundamentally work. So the login is not tied to specific functionality, but to the whole functionality of the app.
The code example bellow is called on an initial screen (before getting inside the app functional areas) every time the app starts to make sure the user has the iCloud going. If the user has iCloud I take him inside the app. If not I stop him and ask him to get iCloud sorted. But I guess that is what they are complaining about here - "User registration that requires the sharing of personal information must be optional or tied to account-specific functionality. Additionally, the requested information must be relevant to the features.".
Which puts myself in a quite confusing situation. Not sure how to resolve the issue. Has anyone has similar issues with CloudKit/iCloud/AppStore Submission? Any insights?
iCloud check code bellow:
func cloudKitCheckIfUserIsAuthenticated (result: (error: NSError?, tryAgain: Bool, takeUserToiCloud: Bool) -> Void){
let container = CKContainer.defaultContainer()
container.fetchUserRecordIDWithCompletionHandler{
(recordId: CKRecordID?, error: NSError?) in
dispatch_async(dispatch_get_main_queue()) {
if error != nil
{
if error!.code == CKErrorCode.NotAuthenticated.rawValue
{
// user not on icloud, taki him there
print("-> cloudKitCheckIfUserIsAuthenticated - error fetching ID - not on icloud")
// ERROR, USER MUST LOGIN TO ICLOUD - LOCK HIM OUTSIDE THE APP
result(error: error, tryAgain: false, takeUserToiCloud: true)
}
print("-> cloudKitCheckIfUserIsAuthenticated - error fetching ID - other error \(error?.description)")
// OTHER ERROR, TRY AGAIN
result(error: error, tryAgain: true, takeUserToiCloud: false)
}
else
{
let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase
publicDatabase.fetchRecordWithID(recordId!,
completionHandler: {(record: CKRecord?, error: NSError?) in
if error != nil
{
// error getting user ID, try again
print("-> cloudKitCheckIfUserIsAuthenticated - error fetching user record - Error \(error)")
// ERROR, TRY AGAIN
result(error: error, tryAgain: true, takeUserToiCloud: false)
}
else
{
if record!.recordType == CKRecordTypeUserRecord
{
// valid record
print("-> cloudKitCheckIfUserIsAuthenticated - fetching user record - valid record found)")
// TAKE USER INSIDE APP
result(error: error, tryAgain: false, takeUserToiCloud: false)
}
else
{
// not valid record
print("-> cloudKitCheckIfUserIsAuthenticated - fetching user record - The record that came back is not a user record")
// ERROR, TRY AGAIN
result(error: error, tryAgain: true, takeUserToiCloud: false)
}
}
})
}
}
}
}
Initially my application would ask the user to login to iCloud on launch screen. If the users did not have an iCloud account functional they would not be able to get inside the app.
Solution
Let the user get inside the app and click on the main sections. In fact the app was completely useless but the user could see it's odd empty screens without the ability to save or load anything. By the time they tried to load or save things I would prompt them the needed to login on iCloud to make the app usable.
Practical outcome
I don't think apple's change request added anything of value to the UX. In fact it just added complexity for the user to understand what he can do and what he cannot.
As an example Facebook locks the user outside if the user do not provide his personal details because without this data the application has absolutely no use and that is my case... You could arguably say the user should be able to get inside, but what he would see or do? Then you would have to cater for all the exceptions this UX builds and throw warnings for the user to fix the account issue everywhere on an annoying pattern of warnings.
So I am not sure "how" Facebook could get it approved and I could not.
Although I got the app approved I disagree Apple feedback improved the application in any way.

Adding users to firebase

I'm having a bit of trouble adding users to Firebase. If anyone could help me out with this, it would be significantly appreciated.
Here is my code:
var myRootRef = Firebase(url:"https://plattrapp.firebaseio.com/users")
myRootRef.createUser(emailSignUpEntered, password: passwordSignUpEntered,
withValueCompletionBlock: { error, result in
if error != nil {
// There was an error creating the account
} else {
let uid = result["uid"] as? String
println("Successfully created user account with uid: \(uid)")
}
})
It does display in the println statement within my debugger that a user has been created, but doesn't actually display within my firebase database.
Anything I may be doing wrong?
Firebase Authentication does not automatically create any information about the user in the associated database.
Most applications end up creating this information from their own code under a top-level users node. This is covered in the section called "Storing User Data" in the Firebase programming guide for iOS.
It is in general a good idea to read the Firebase documentation on the topic that you are working on. It will prevent a lot of grey/lost hair and wasted time.

Logout user when deleted from Parse data browser

I have a couple hundred users that I need to remove from my parse app. However, when I delete the user accounts the users are still able to use the app fully without a problem. Is there anyway to "force" the logout remotely? Or what else would you suggest? Thanks!
It sounds like the user is being cached on the device and I don't think parse has a remote way to clear cached data on there. I like to put a user refresh(now fetch since refresh is deprecated) function when app opens to get the latest data for that user.
You could put a fetch function when the app opens and if it returns a specific error, it would mean the user doesn't exist and then set the current user to nil. I'm not sure which error it returns and I'm at work so I can't try it right now. I would hope that if the user doesn't exist, it would return kPFErrorUserWithEmailNotFound = 205...
Here are the error codes: https://parse.com/docs/ios/api/Constants/PFErrorCode.html
You will have to give it a try but I am thinking something like this (sudo-code):
post.fetchIfNeededInBackgroundWithBlock {
(post: PFObject?, error: NSError?) -> Void in
if let someError = error {
if someError = kPFErrorUserWithEmailNotFound {
// User doesn't exist!
}
} else {
// User exists and is fetched successfully
}
}

Resources