繁体   English   中英

如何在childByAutoID下访问Firebase数据?

[英]How can I access Firebase data under a childByAutoID?

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

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

这是我要访问的数据Firebase数据

在此处输入图片说明

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

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

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

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

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

您可以观察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]
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM