How to avoid Firebase fatal error: unexpectedly found nil while unwrapping an Optional value?

强颜欢笑 提交于 2019-12-13 01:14:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!