elizabeth
elizabeth

Reputation: 13

Retrieving Image From Firebase

The app run successfully , but the image did not show up in the table cell.

let dbRef = FIRDatabase.database().reference().child("restaurants/restaurantImage")
    dbRef.observe(.childAdded, with: {(snapshot) in
        let downloadURL = snapshot.value as! String
        let storageRef = FIRStorage.storage().reference(forURL: downloadURL)
        storageRef.data(withMaxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            let pic = UIImage(data: data!)
            self.picArray.append(pic!)

        }
        self.tableViewHongKong.reloadData()
    })

Upvotes: 0

Views: 466

Answers (3)

ZassX
ZassX

Reputation: 1369

Even if Callam already answered your question, I am still posting this since it is probably better way for doing it.

Instead of writing all that code just to display one image, you can use Glide which works very well with Firebase plus it is well documented in Firebase Docs. Check it out, it made everything a lot easier for me when I started using it.

https://firebase.google.com/docs/storage/android/download-files#downloading_images_with_firebaseui

Upvotes: 0

Callam
Callam

Reputation: 11539

The images do not appear because you are reloading your table view before any pictures are appended to the array. The data(withMaxSize: starts an asynchronous request that gets a response after you have reloaded the table view.

If you move self.tableViewHongKong.reloadData() inside the data(withMaxSize: response block, you will reload the table view after you append each successfully loaded image.

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54706

You should move self.tableViewHongKong.reloadData() inside your completion handler. With your current code you reload the table before the asynchronous function would finish.

You shouldn't do force unwrapping unless you are 100% sure that data will actually return and that the UIImage initializer will succeed.

let dbRef = FIRDatabase.database().reference().child("restaurants/restaurantImage")
    dbRef.observe(.childAdded, with: {(snapshot) in
        let downloadURL = snapshot.value as! String
        let storageRef = FIRStorage.storage().reference(forURL: downloadURL)
        storageRef.data(withMaxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            guard let imageData = data, let pic = UIImage(data: imageData) else { return }
            self.picArray.append(pic)
            self.tableViewHongKong.reloadData()
        }
    })

Upvotes: 1

Related Questions