2016-11-09 393 views
1

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" 
+0

後期圖像你的firebase結構 –

+0

準備好鏈接我的結構 – LEONID

+0

更新之後上面的評論它sa是我的「類ViewController沒有初始化器」,並在viewDidLoad成爲錯誤:「預期表達式」 – LEONID

回答

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) 
      } 
     } 
    }) 
+0

謝謝:)))) – LEONID

+0

@LeonifNif請接受這個答案,如果它的工作! – Jay

+0

謝謝你!你救了我一天! – Viny76

1

的只是兩行代碼let ref = FIRDatabase.database().reference()沒有指向引用URL,因爲在初始化過程中你的火力點不在你的應用程序委託文件中配置(不叫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("Авторизация Ок!!!")}) 

    } 
+0

不幸的是,沒有工作:( – LEONID