如何在childByAutoID下访问Firebase数据?

时间:2018-08-10 04:19:34

标签: ios swift firebase firebase-realtime-database

我目前正在尝试访问一些以随机子ID存放在数据库中的图书数据。我一直在搜寻其他问题,但是我得到的最远的结果是能够在闭包内访问ID。我不知道如何正确设置完成处理程序以提取ID。

此外,我不知道是否有更简单的方法来解决这个问题?

以下是我要访问的数据: Firebase data

enter image description here

这是我当前需要完成处理程序的代码吗?

func getChildID(department: String, course: String) {

        let parentRef = myDatabase.child("departments").child(department).child(course)

        parentRef.observeSingleEvent(of: .value) { (courseSnapshot) in
            if let data = courseSnapshot.value as? [String:String] {

                for value in data {
                    let isbn = value.value
                    if isbn != "ISBN" {

                        myDatabase.child("listings").child("\(isbn)").observeSingleEvent(of: .value, with: { (snapshot) in
                            let dictionary = snapshot.value as! NSDictionary
                            for key in dictionary.keyEnumerator() {
                                let myKey = key as! String
                                return
                            }
                        })
                    }
                }
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

我们在这里。这个问题的答案。但是,我在对问题的评论中提到,可以改进结构。但是,每个列出的子项下可能有更多的子项,因此此答案可以解决。

这只是打印每个作者的名字,但它显示了如何获取它,因此应将答案扩展到其他子节点。

let listingsRef = self.ref.child("listings")
listingsRef.observeSingleEvent(of: .value, with: { snapshot in
    for child in snapshot.children {
        let autoIdSnap = child as! DataSnapshot
        for autoChild in autoIdSnap.children {
            let childSnap = autoChild as! DataSnapshot
            let dict = childSnap.value as! [String: Any]
            let author = dict["author"] as! String
            print(author)
        }
    }
})

哦,也许会有更好的结构

listings
   childByAutoId
      author: "Some author"
      listing: 9780184888
   childByAutoId
      author: "Another author"
      listing: 9799292598

编辑:如果每个列表下只有一个,只有一个childByAutoId,则可以消除上面的循环并执行此操作

let listingsRef = self.ref.child("listings")
listingsRef.observeSingleEvent(of: .value, with: { snapshot in
    for child in snapshot.children {
        let autoIdSnap = child as! DataSnapshot //each listing
        let childDict = autoIdSnap.value as! [String: Any] //a dict of items within the listing
        let firstKey = childDict.keys.first! //the key to the first item
        let valuesDict = childDict[firstKey] as! [String: Any] //the values for that key
        let author = valuesDict["author"] as! String //the author value
        print(author)
    }
})

答案 1 :(得分:1)

您可以观察到childByAutoId()之前的最后一个对象的更改,在这种情况下,它将是“列表”,然后根据该对象创建模型。

override func viewDidLoad() {
    super.viewDidLoad()

    Auth.auth().signInAnonymously() { (user, error) in
        if error == nil{
            print("sign in successful")
        }
    }

    let query = myDatabase.child("listings")

    query?.removeAllObservers()

    query?.observe(.value, with: { snapshot in
        if snapshot.exists() {
            let booksSnapshot = Books(snap: snapshot)

            for children in booksSnapshot.books{
                let childByAutoId = children.value as! NSDictionary

                for books in childByAutoId{
                    let key = books.value as! NSDictionary

                    let book: Books = Books(fromJson: JSON())

                    book.author = key["author"] as! String
                    book.title = key["title"] as! String
                    book.price = key["price"] as! Int

                    print(book.price)
                }
            }
        }
    })
}

//型号 ///注意:您必须安装'SwiftyJSON'才能创建此模型

import Foundation
import SwiftyJSON
import Firebase

class Books : NSObject{

var author : String!
var title : String!
var price : Int! // you can add more variables later
var books : [String: AnyObject]!

init(fromJson json: JSON!){
    if json.isEmpty{
        return
    }
    author = json["author"].stringValue
    title = json["title"].stringValue
    price = json["price"].intValue
}

/**
 * Instantiate the instance using the passed json values to set the properties values
 */
init(snap: DataSnapshot){
    let json = snap.value as! NSDictionary
    books = json as! [String: AnyObject]
}
}