简体   繁体   中英

Firebase App crashing on startup swift

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

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
    }
})

I'm not quite sure where you are initializing your code. Possible solutions:

  1. Use guard statement guard let userID = Auth.auth().currentUser?.uid else {return}

  2. Try putting this code in a function that will return an optional string.

  3. If you are trying to check if the user exists before didFinishLaunchingWithOptions, make an if else statement or guard statement like the one above. if Auth.auth().currentUser?.uid != nil
  4. If you are using Cocoapods, try with pod update
  5. If these are not working, try reinstalling the pod.
  6. Call FirebaseApp.configure() in didFinishLaunchingWithOptions in appDelegate and return true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM