问题
I am trying to read from Firebase and set the label to the value I get
This is what the top of my ViewController class looks like:
import UIKit
import Firebase
class ProfileTabViewController: UIViewController {
//MARK: Properties
@IBOutlet weak var nameLabel: UILabel!
var userName = "userName"
I have a Firebase Reference at
var currentUserName = Firebase(url: "https://buzzmovieios.firebaseio.com/users/884962b7-9fd8-49db-b172-1ad7cb1414f4/Name")
The random string is the uid returned by Firebase.
I am trying to get the user name in the viewDidAppear() method:
override func viewDidAppear(animated: Bool) {
print(currentUserName)
currentUserName.observeEventType(.Value) { (snap: FDataSnapshot!) in
let name = snap.value as! String
self.nameLabel.text = name
}
}
the let name line works fine.
print(name)
This line:
self.nameLabel.text = name
causes:
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
I've tried
let name = snap.value as? String
and it doesn't work.
This is what my Firebase looks like:
buzzmovieios
users
--884962b7-9fd8-49db-b172-1ad7cb1414f4
Major: CS
Name: Shawn
--8880069d-1944-493d-8246-8119fc4bfc81
and so on.
How can I avoid this unwrapping error? Thanks!
Note: I'm running XCode 7.3
回答1:
please use if let to unwrap optionals like
if let name = snap.value as? String{
self.nameLabel.text = name
}
and also check that your outlets connected properly otherwise it crashed..
来源:https://stackoverflow.com/questions/36564178/how-to-avoid-firebase-fatal-error-unexpectedly-found-nil-while-unwrapping-an-op