简体   繁体   中英

Can't populate an array with data from Firebase database

Below I try to make an array ChatListings, but it doesn't work.

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. 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:

"-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:

    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. 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? It has been a very frustrating experience working with Firebase and I definitely regret it. 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 .


Update . Turns out using NSDictionary , rather than Dictionary , fixed the dict constant crashes. But, besides compiler bugs, still not clear why...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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