简体   繁体   English

无法使用Firebase数据库中的数据填充数组

[英]Can't populate an array with data from Firebase database

Below I try to make an array ChatListings, but it doesn't work. 下面,我尝试创建一个数组ChatListings,但是它不起作用。

let chatRef = FIRDatabase.database().reference().child("chatListings")


override func viewDidLoad() {
    super.viewDidLoad()
    let firstQuery = chatRef.queryOrdered(byChild: "userID").queryEqual(toValue: userID)
    firstQuery.observe(FIRDataEventType.value, with: { snapshot in
        for child in snapshot.children {
            print("child is \(child)")
            if let dict = snapshot.value as? Dictionary<String, AnyObject>{
                print("dict is \(dict)")
                let roomKey = dict["chatRoomKey"] as! String
                let oUID = dict["otherUserID"] as! String
                let oUserName = dict["otherUserName"] as! String
                let oProfilePic = dict["otherUserProfilePic"] as! String
                let userIDTemp = dict["userID"] as! String
                chatListing = ChatListing(chatRoomKey: roomKey, UID: userIDTemp, name: oUserName, otherUserID: oUID, otherUserProfilePicURL: oProfilePic)
                chatListings.append(chatListing)
            }
        }
        print("chatListings = \(chatListings)")
    })
}

This crashes saying that the compiler unexpectedly found nil while unwrapping an Optional value. 崩溃表示编译器在解开Optional值时意外地找到nil。 I don't know why it won't work. 我不知道为什么它不起作用。 I've tried every which way I can find to extract the data that the compiler reads moments before crashing or failing to fill an array of my 'chatlisting' objects. 我已经尝试了各种方法来提取出编译器在崩溃或无法填充“聊天”对象数组之前读取的数据。

Here's an example of the data that the compiler reads but cannot extract with maybe 4 different coding attempts: 这是编译器读取但无法通过4种不同的编码尝试提取的数据的示例:

"-KjdSF97Q2z3afXzkwQ9": {
chatRoomKey = "-KjdSF97Q2z3afXzkwQ9";
messages =     {
    "-KjdSOVTsg8jEy6SeEA2" =         {
        MediaType = PHOTO;
        fileUrl = "https://firebasestorage.googleapis.com/v0/b/preollify.appspot.com/o/mget8KN2nHe4sOhbnWTixYvCOrr2%2F515963239.371526?alt=media&token=6cb12ec1-5bdb-43a1-ab49-90c90570b341";
        senderId = mget8KN2nHe4sOhbnWTixYvCOrr2;
        senderName = Michael;
    };
    "-KjdSPxpNT0pkQ1y5-_1" =         {
        MediaType = VIDEO;
        fileUrl = "https://firebasestorage.googleapis.com/v0/b/preollify.appspot.com/o/mget8KN2nHe4sOhbnWTixYvCOrr2%2F515963229.282051?alt=media&token=04671c8e-d7f1-49f2-81d0-09836c034ae2";
        senderId = mget8KN2nHe4sOhbnWTixYvCOrr2;
        senderName = Michael;
    };
    "-KjdVaVTfbaC-3S-91-A" =         {
        MediaType = TEXT;
        senderId = mget8KN2nHe4sOhbnWTixYvCOrr2;
        senderName = Michael;
        text = The;
    };
};
otherUserID = aRandomUser3611;
otherUserName = Michael;
otherUserProfilePic = "https://firebasestorage.googleapis.com/v0/b/preollify.appspot.com/o/ProfilePictures%2Fmget8KN2nHe4sOhbnWTixYvCOrr2%2FmediumProfilePicture.jpg?alt=media&token=d88afa5d-0db7-4ce2-95c9-3038ff592e9f";
userID = mget8KN2nHe4sOhbnWTixYvCOrr2;

I'm trying to extract all the data but the messages part, which I plan on doing later in the app. 我正在尝试提取除消息部分之外的所有数据,我计划稍后在应用程序中进行提取。

This data (excluding the "messages" part) gets written in the chatViewController's viewDidLoad like this: 此数据(不包括“消息”部分)被写入chatViewController的viewDidLoad中,如下所示:

    let preMessageRef = chatRef.childByAutoId()
    chatListingID = preMessageRef.key
    let initialChatRoomData = ["chatRoomKey": chatListingID, "otherUserID": otherUID, "otherUserName": otherUserName, "otherUserProfilePic": otherUserProfilePicURLString, "userID": userID]
    preMessageRef.setValue(initialChatRoomData)

Retrieving data from Firebase Database has been completely hit or miss for me, with copying the successful attempts of extracting data rarely working twice. 从Firebase数据库检索数据对我来说完全是命中注定或错过,复制成功提取数据的尝试很少能成功两次。 Their documentation is minimal to the point of leaving out way too much as it provides little help for how to extract data in real world contexts. 他们的文档很少,以至于省去了太多,因为它对如何在现实环境中提取数据几乎没有帮助。 Why do people like Firebase? 人们为什么喜欢Firebase? It has been a very frustrating experience working with Firebase and I definitely regret it. 使用Firebase经历了非常令人沮丧的经历,对此我深表遗憾。 But it's probably too late to turn back and go with something better, ie a platform that provides clear instruction for how to get it to work. 但是现在回过头去选择更好的东西可能为时已晚,例如,一个提供明确说明如何使其工作的平台。

I think you just have a silly typo. 我认为您只是一个愚蠢的错字。 Try this: 尝试这个:

let childData = child as! FIRDataSnapshot
print("child key: \(childData.key)")
if let dict = childData.value as? Dictionary<String, AnyObject> {
    ...
}

that is, use child instead of snapshot . 也就是说,使用child而不是snapshot


Update . 更新 Turns out using NSDictionary , rather than Dictionary , fixed the dict constant crashes. 事实证明,使用NSDictionary而不是Dictionary修复了dict常量崩溃。 But, besides compiler bugs, still not clear why... 但是,除了编译器错误外,仍然不清楚原因...

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

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