无法在Firebase中获取节点的价值

时间:2016-11-09 06:25:26

标签: ios swift firebase firebase-realtime-database

My structure

我阅读了很多例子,其中大多数都有旧式(即使是今年写的)。请帮忙了解我的代码出错的地方?它已建成但我无法获得值123456。

import UIKit
import Firebase

class ViewController: UIViewController {
  @IBOutlet weak var val_txt: UITextField!
  let ref = FIRDatabase.database().reference()
  var barcode = 0  

  override func viewDidLoad() {
    super.viewDidLoad()
    FIRAuth.auth()?.signIn(withEmail: "*****@gmail.com", password: "*****", completion: {(user,error) in print("Авторизация Ок!!!")})

  }
  @IBAction func getData_btn(_ sender: Any) {
    ref.child("goods").child("1").observe(FIRDataEventType.value, with: {(snapshot) in
    let postDict = snapshot.value as? [String:AnyObject] ?? [:]
    print(postDict["barcode"] as? Int)
  })
  print(barcode)
}

我已经更改了代码以便理解打印是否执行,我发现它没有

print("Method started")
ref.child("goods").child("1").observe(FIRDataEventType.value, with:{(snapshot) in
    let postDict = snapshot.value as? [String:AnyObject] ?? [:]
    print("Method is executing")
  })
  print("Method completed")

我只得到两行打印

"Method started"
"Method completed"

3 个答案:

答案 0 :(得分:2)

如果您只想要" 1":

的价值
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
ref.child("goods").child("1").observeSingleEvent(of: .value, with: { (snapshot) in
            let id = snapshot.childSnapshot(forPath: "barcode")
            print(id)
        })

但如果您想要所有条形码:

var ref: FIRDatabaseReference!
    ref = FIRDatabase.database().reference()
    ref.child("goods").observeSingleEvent(of: .value, with: { (snapshot) in
        if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

            for snap in snapshots
            {
                let barcode = snap.childSnapshot(forPath: "barcode").value! as! String
                print(barcode)
            }
        }
    })

答案 1 :(得分:1)

在您的代码中let ref = FIRDatabase.database().reference()请勿指向引用网址,因为在初始化期间,您的firebase未在您的应用委托文件中配置(不称为FIRApp.configure())。

所以放入func viewDidLoad()如下:

import UIKit
import Firebase

class ViewController: UIViewController {
  @IBOutlet weak var val_txt: UITextField!
  let ref:FIRDatabaseReference!
  var barcode = 0  

  override func viewDidLoad() {
    super.viewDidLoad()
    ref:FIRDatabaseReference = FIRDatabase.database().reference()
    FIRAuth.auth()?.signIn(withEmail: "*****@gmail.com", password: "*****", completion: {(user,error) in print("Авторизация Ок!!!")})

  }

答案 2 :(得分:0)

使用以下代码可以帮助您。

let ref = FIRDatabase.database().reference()
ref.child("goods").child("1").observe(DataEventType.value, with: {(snapshot) in
            if snapshot.childrenCount>0 {
                for transactions in snapshot.children.allObjects as! [DataSnapshot] {
                    var  obj = transactions.value as! [String:AnyObject]
                    print(obj["barcode"] as! Int)
                }
            }
})