Populating an UICollectionView to Firebase

Question

I'm trying to populate a collection view with data from a Firebase Database. I'm making following call in my viewdidload function:

ref = FIRDatabase.database().reference(withPath: "Profiles")

handle = ref.queryOrdered(byChild: title!).observe(.value, with: { snapshot in

    var items: [Profiles] = []

    if snapshot.value is NSNull {

       print("NIL!!")

    } else {
       for item in snapshot.children {

           let profile = Profiles(snapshot: item as! FIRDataSnapshot)

               items.append(profile)
           }

            self.profiles = items
            self.collectionView?.reloadData()
        }
    }) { (error) in
        print(error.localizedDescription)
    }

I'm getting the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

and the compiler highlights the following piece of code:

handle = ref.queryOrdered(byChild: title!).observe(.value, with: { snapshot in

I'm not understanding what the issue is, and dont understand how to fix it?!


Show source
| swift   | ios   | firebase   2017-01-07 02:01 1 Answers

Answers to Populating an UICollectionView to Firebase ( 1 )

  1. 2017-01-07 04:01

    It sounds like you're confusing the UIViewController's title member with the Firebase child you're using the query for. If you have a child named title in your data structure and want to query based on that, just replace your query statement with this:

    ref.queryOrdered(byChild: "title").observe(.value, with: { snapshot in
        // your code
    })
    

    The only way you'd get the error you're getting is if the variable you're using (title) has nil.

Leave a reply to - Populating an UICollectionView to Firebase

◀ Go back