Firebase addStateDidChangeListener - ios

I am pretty new to Firebase. I am trying to check if the user is logged in or not, and by referring to the Firebase doc, the recommended way of doing it would be adding a FIRAuthStateDidChangeListenerHandle.
My code is as follows:
handle = FIRAuth.auth()?.addStateDidChangeListener({ (auth, user) in
//here, we add code to see if we are supposed to be loggin or not
print("hello world")
if user != nil{
self.isLogin = true
}else{
self.isLogin = false
}
})
However, after I checked, it seems that FirAuth.auth() is a nil and the entire block is not called at all.
Any one knows what is wrong here?

This looks like an improperly set up Firebase. Did you follow all the steps here? Specifically, did you, in your AppDelegate, call FIRApp.configure()? Without this configuration call your FIRAuth would likely be nil.

Related

firestore collection path giving bugs with constants value and String value

So my goal is to get rid of these bugs completely. I am in a dilemma where each decision leads to a bug.
The first thing I can do that eventually becomes an issue is use a String-interpolated collection path in all my query functions like so:
func getEventName() {
listener = db.collection("school_users/\(user?.uid)/events").order(by: "time_created", descending: true).addSnapshotListener(includeMetadataChanges: true) { (querySnapshot, error) in
if let error = error {
print("There was an error fetching the data: \(error)")
} else {
self.events = querySnapshot!.documents.map { document in
return EventName(eventName: (document.get("event_name") as! String))
}
self.tableView.reloadData()
}
}
}
The thing with this is, when I run the app on the simulator, I am restricted from pressing buttons and then sometimes I can press them and then sometimes they get restricted again. This bug is so confusing because it makes no sense where it springs from.
The other issue is I can use a Constants value in all the query functions in my collections path.
static let schoolCollectionName = "school_users/\(user?.uid)/events"
This is nested in a Firebase struct within the Constants struct. In order to keep Xcode from giving errors I create a let users = Auth.auth().currentUser variable outside the Constants struct. The issue with this value is that when I put that in all of my query functions collection paths, all the buttons are accessible and selectable all the time, but when a user logs out and I log in as a new user, the previous user's data shows up in the new user's tableview.
It would obviously make more sense to use the Constants value because you prevent typos in the future, but I can't figure out how to get rid of the bug where the old user's data shows up in the new user's tableview. Thanks in advance.
The user id should definitely not be a constant. What it sounds like is that right now, you have no reliable way to change users -- your setup probably depends on which user is logged in at app startup, since that's where your variable gets set.
I would do something more like this:
func getEventName() {
guard let user = Auth.auth().currentUser else {
//handle the fact that you don't have a user here -- don't go on to the next query
return
}
listener = db.collection("school_users/\(user.uid)/events").order(by: "time_created", descending: true).addSnapshotListener(includeMetadataChanges: true) { (querySnapshot, error) in
Note that now, user.uid in the interpolated path doesn't have the ? for optionally unwrapping it (which Xcode is giving you a warning for right now). It will also guarantee that the correct query is always made with the currently-logged-in user.
Regarding being able to press the buttons, that sounds like an unrelated issue. You could run your app in Instruments and check the Time Profiler to see if you have long-running tasks that are gumming up the main/UI thread.

Facebook AccessToken returns nil

I can no longer sign-in-with-Facebook inside my app as AcessToken return nil...
Here is my function:
let accessToken = AccessToken.current
guard let accessTokenString = accessToken?.tokenString else {
print("bruh")
return
}
It currently prints the "bruh".
It was working the other days!
I didn't change anything inside that file. But I changed the Project Name and the Bundle Identifier. Could this have anything to do with the error?
UPDATE: I deleted the old Facebook-Project and created a new one with the correct Bundle-ID. I also changed the ID and Secret Token inside Firebase.
Is there anything else I need to do??? really annoying ...
Is there maybe a way to show an error to see what the actual problem is?
It seems to be about changing of Bundle Identifier,
You should set the new one on https://developers.facebook.com/
I fixed the issue! The problem was that I had the old ID inside my info.plist

Firebase Database setValue: or removeValue failed: permission_denied iOS

I'm trying to write data to Firebase Database but I keep receiving the following error when my saved button is pressed.
2016-12-02 11:09:42.548 StartupNow[1482:60415] [FirebaseDatabase] setValue: or removeValue: at /test/-KY-VpLZWbp4vjF3BpMk failed: permission_denied
Things I've tried:
I've made sure my .read and .write rules were set to true in my console, reconnected my savedButtonPressed button, and wrote the Firebase reference in a function and called it in my savedButtonPressed() method.
Extra Resource Here is the tutorial I'm following along. https://youtu.be/F42CzqIBxHQ?t=4m14s
var ref: FIRDatabaseReference?
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
}
#IBAction func saveButtonPressed() {
// TODO: Post data to Firebase
firebaseChild()
print("********************************")
print("********************************")
}
func firebaseChild () {
ref?.child("Test").childByAutoId().setValue("Hello Firebase")
}
I had a similar issue. It was resolved by resetting the read / write rules for the database. If you changed your rules try reseting them to the default.
Warning: These rules allow anyone to read and write to your database!
Default Rules for Real-time Database
{
"rules": {
".read": true,
".write": true
}
}
Default Rules for Cloud Firestore
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
FreddieOh and I chatted over Slack, and the problem was that the database that was listed in the GoogleService-info.plist file didn't match up with the one he was editing. (It looks like maybe in this case, he had deleted and recreated the project in the Firebase console, but hadn't updated the plist file.)
If you find yourself in the same situation where you've set your read and write access to true and are still getting permission denied errors, open up your GoogleService-info.plist file and look at the entry for DATABASE_URL. Then go to the Firebase Database in your project, look at the top of the data tab, and confirm that the URL listed there is the same as the one in your plist file.
I suppose the other thing to check for would be that you updated your database rules to allow global access but forgot to click the Publish button. That... may have happened to me at one point. :)
Go to your Firebase console, and perform following steps which is identify in image.
Please lookup image and follow these steps. If you are beginner and facing problem in image. I make little video about error.
Video Solution :
https://youtu.be/FcQCPqckvqo
Image Solution
I have solved the same issue after trying to use every resource. The only solution is that
Go to fireBase Console -->select your project -->Go to database -->select the Rules("Show in the mid next to the Data")-->make the make both option true
{
"rules": {
".read": true,
".write": true
}
this will be work perfectly
Make sure to select real time database and edit the rule then publish .

Why would this swift code still be performing the segue?

I have a conditional segue set up that will perform the segue set up the following way:
override func viewDidAppear(animated: Bool) {
if PFUser.currentUser() != nil{ //if the user is logged in previously
self.performSegueWithIdentifier("AlreadySignedIn", sender: self)
print(PFUser.currentUser()?.username)
}
Even deleting all users from the database (Parse), the segue is still performed. I don't think the problem is with the syntax of this particular code, but does anyone have any ideas what might be causing this?
PFUser.currentUser() is not aware about the users that you have in your DB.
when you log in to Parse via parse ios SDK. the parse IOS SDK save the currentUser instance on your disk and when you specify PFUser.currentUser() the parse IOS SDK check if the user was logged in before (by checking if it is stored on the disk). if you want that the PFUser.currentUser() will return nil you must call PFUser.logout() function. this function will clear the current logged in user.

Parse with Swift - User Queries

Im trying to query my Parse User database in order to create a friend request between two users. The user inputs a user name that they want to add as a friend. However, when I try to query the database, I get a "EXC_BAD_ACCESS" error on the line where I am adding the condition. Not sure why Im getting this error, as its my understanding it has to do with trying to access memory already freed. Anything that you can do to help would be very appreciated!
var friendship = PFObject(className: "Friends")
var findUser:PFQuery = PFUser.query()
findUser.whereKey("username",equalTo:username2) //program crashes here for some reason
findUser.getFirstObjectInBackgroundWithBlock {
(user2, error: NSError!) -> Void in
if user2 == nil {
println("Failure")
} else {
println("Successfully retrieved the object.")
friendship["user1"] = PFUser.currentUser().objectId
friendship["user2"] = user2.objectId
friendship["pending"] = true
friendship.save()
}
}
Set a breakpoint in the compiler and navigate the steps until you hit the crash so you can understand exactly at which point it crashes a troubleshoot further from there with the better understanding.
Also once it has crashed use LLDB print out po ivar to check if any of your ivars got instantiated and which ones are empty or execute dubious functions with exp func.
So... It works today. Not sure what happened. Co-Developer and I reorganized frameworks and everything works fine now. Thank you for your help everyone. I appreciate the responses :)

Resources