Reputation: 896
I have a ios app connected to my firebase, in which I have a class where I have defined all the links to firebase-database.
AppDelegate.swift contains aa init()
method so, Firebase is the first one to be initialized.
override init() {
super.init()
FirebaseApp.configure()
}
Firebase Dataservice where all DB paths are defined.
import Firebase
import FirebaseDatabase
let DB_URL: DatabaseReference = Database.database().reference()
let ST_URL: StorageReference = Storage.storage().reference()
let uid = Auth.auth().currentUser?.uid
class FBDataservice {
//... other code
}
Now as soon as I Launch the app, I get an error
fatal error: unexpectedly found nil while unwrapping an Optional value
This error is made on the uid definition in dataservice class.
Now, As far as I understand, This is because the uid may be initialized even when there is no user.
I am out of Ideas on how to implement this. I have many references to uid in my entire project. What is the most apt way to perform this.
Thanks
Upvotes: 0
Views: 606
Reputation: 1231
I'm not quite sure where you are initializing your code. Possible solutions:
Use guard statement guard let userID = Auth.auth().currentUser?.uid else {return}
Try putting this code in a function that will return an optional string.
if Auth.auth().currentUser?.uid != nil
pod update
FirebaseApp.configure()
in didFinishLaunchingWithOptions in appDelegate and return true.Upvotes: 0
Reputation: 38833
You might want to use the observeAuthEventWithBlock
.
To listen for changes in the authentication state, attach an event observer with observeAuthEventWithBlock. If there is no user currently authenticated, authData will be nil.
You implement it like this according to the reference:
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com")
ref.observeAuthEventWithBlock({ authData in
if authData != nil {
// user authenticated
println(authData)
} else {
// No user is signed in
}
})
Upvotes: 3