不能使用实例成员' ref'初始化错误

时间:2017-01-13 10:23:26

标签: swift firebase firebase-realtime-database

我面对这个错误一切都很好,我想要打印#34; 12356"在控制台,但我收到此错误,我不知道为什么会发生这种情况,这里是 Firebase结构 enter image description here

这是xcode错误 enter image description here

,这是代码

 import UIKit
 import Firebase
 import FirebaseDatabase

class TestViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}


var ref  = FIRDatabase.database().reference()


let root = ref.child("Items").child("Flate").child("12356")

root.observeSingleEvent(of: .value, with: { snapshot in

if !snapshot.exists() { return }

//print(snapshot)

if let myfRateA = snapshot.value["fRateA"] as? String {
print(myfRateA)
}
if let myfRateB = snapshot.value["fRateB"] as? String {
print(myfRateB)
}
})


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

1 个答案:

答案 0 :(得分:1)

您没有将代码放在正确的位置,因为它不在任何方法或功能之内。把它放在一个函数的体内就像这样:

func printChildren(){

let ref  = FIRDatabase.database().reference()


let root = ref.child("Items").child("Flate").child("12356")

root.observeSingleEvent(of: .value, with: { snapshot in

if !snapshot.exists() { return }

//print(snapshot)

let myfRateA = (snapshot.value as? NSDictionary)?["fRateA"] as? String ?? ""
print(myfRateA)
let myfRateB = (snapshot.value as? NSDictionary)?["fRateB"] as? String ?? ""
print(myfRateB)

})

}

并在 viewDidLoad() 中调用它,如下所示:

override func viewDidLoad() {
    super.viewDidLoad()
    self.printChildren()
}