简体   繁体   中英

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

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

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.

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

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