如何避免Firebase致命错误:意外地发现零,而解包一个可选值? [英] How to avoid Firebase fatal error: unexpectedly found nil while unwrapping an Optional value?
问题描述
我正在尝试从Firebase中读取数据,并将标签设置为我获得的值。这是我的ViewController类的顶部:
$ p $
导入UIKit
导入Firebase
类ProfileTabViewController:UIViewController {
/ / MARK:Properties
@IBOutlet weak var nameLabel:UILabel!
var userName =userName
我在Firebase Reference中
var currentUserName = Firebase(url:https://buzzmovieios.firebaseio.com/users/884962b7-9fd8-49db-b172-1ad7cb1414f4/Name )
随机字符串是Firebase返回的uid。
我试图在viewDidAppear()方法中获取用户名:
override func viewDidAppear(animated :bool){
print(currentUserName)
currentUserName.observeEventType(.Value){(snap:FDataSnapshot!)in
let name = snap.value as! String
self.nameLabel.text = name
}
}
让名字行工作正常。
print(name)
这行:
self.nameLabel.text = name
$ c $
致命错误:意外发现无而解开一个可选的值
(lldb)
我已经尝试了
让name = snap.value as?字符串
不起作用。
这就是我的Firebase的样子:
<$ p $ b> buzzmovieios
用户
--884962b7-9fd8-49db-b172-1ad7cb1414f4
专业:CS
名称:Shawn
--8880069d -1944-493d-8246-8119fc4bfc81
等等。
我怎样才能避免这个解包错误?谢谢!
$ b
注意:我正在运行XCode 7.3
请使用,如果让解包optionar像 如果让name = snap.value as?字符串{
self.nameLabel.text = name
}
你的网点正确连接,否则坠毁..
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
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..
这篇关于如何避免Firebase致命错误:意外地发现零,而解包一个可选值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!