我试图从我的 firebasedb 中获取值,在运行时, ref.observeSingleEvent(of: .value, with: { snapshot in
) 导致 fatal error 在展开可选值时意外发现 nil值
。我确信你可以告诉我...我不知道我在做什么...提前谢谢您...
func geths() -> Int{
var sch:Int = 0
var nam:String = ""
print("start geths")
ref.observeSingleEvent(of: .value, with: { snapshot in
if (snapshot.exists()){
print("snapexist")
if let snapval = snapshot.value as? [String:AnyObject]{
let hs = snapval["hs"] as? String
let name = snapval["name"] as? String
self.hso = hs!
self.nameo = name!
nam = self.nameo
if let myNumber = NumberFormatter().number(from: self.hso) {
let i = myNumber.intValue
sch = i
}else{
sch = 0
}
}else{
print("error")
}
}else{
print("error")
}
})
return sch
}
编辑************ 仍然不起作用:(同样的错误
func geths() -> Int{
var sch:Int = 0
var nam:String = ""
print("start geths")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if (snapshot.exists()){
print("snapexist")
let snapval = snapshot.value as? NSDictionary
let hs = snapval?["hs"] as? String ?? ""
let name = snapval?["name"] as? String ?? ""
if (hs != nil){
self.hso = hs
}else{
self.hso = "0"
}
if (name != nil){
self.nameo = name
}else{
self.nameo = "bob"
}
nam = self.nameo
if let myNumber = NumberFormatter().number(from: self.hso) {
let i = myNumber.intValue
sch = i
}else{
sch = 0
}
}else{
print("error")
}
})
return sch
}
最佳答案
像这样创建 firebase 引用:
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
有关更多详细信息,请访问此链接: https://firebase.google.com/docs/database/ios/read-and-write
关于ios - 从 FirebaseDB 获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43682794/