Adar.L
Adar.L

Reputation: 3

Retrieve firebase Image - ImageView

Hello everyone I am trying to take my image from the firebase database and present it into an image view as the profile image of the user. The first thing I do is create a method to retrieve the photo data in an array


class PhotoService {
    
    static func retrievePhotos(completion: @escaping ([Photo]) -> Void) {
        
        //get a databas refrence
        let db = Firestore.firestore()
        
        //get data from "photos" collection
        db.collection("photos").getDocuments { (snapshot, Error) in
            
            //check for errors
            if Error != nil {
                //error in retrieving photos
                return
            }
            
            //get all the documents
            let documents = snapshot?.documents
            
            //check that documents arent nil
            if let documents = documents {
                
                //create an array to hold all of our photo structs
                var photoArray = [Photo]()
                
                //loop through documents, get a photos struct for each
                for doc in documents {
                    
                    //create photo struct
                    let p = Photo(snapshot: doc)
                    
                    if p != nil {
                        
                        //store it in an array
                        photoArray.insert(p!, at: 0)
                        
                    }
                    
                }
                
                //pass back the photo array
                completion(photoArray) 
                
            }
            
        }
        
    }

Then I call that class and attempt to display the Image in the image view


@IBOutlet var profilePictureImageView: UIImageView!
        
    var photos = [Photo]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
                
        //call the photo service to retrieve the photos
        PhotoService.retrievePhotos { (retrievedPhotos) in
            
            //set the photo array to the retrieved photos
            self.photos = retrievedPhotos
            
            //make the image view a circle
            self.profilePictureImageView.layer.cornerRadius = self.profilePictureImageView.bounds.height / 2
            self.profilePictureImageView.clipsToBounds = true
            
            //make the image view display the photo
            var photo:Photo?
            
            func displayPhoto(photo:Photo) {
                
                //check for errors
                if photo.photourl == nil {
                    return
                }
                
                //download the image
                let photourl = URL(string: photo.photourl!)
                
                //check for erorrs
                if photourl == nil {
                    return
                }
                
                //use url session to download the image asynchronously
                let session = URLSession.shared
                
                let dataTask = session.dataTask(with: photourl!) { (data, response, Error) in
                    
                    //check for errors
                    if Error == nil && data != nil {
                        
                        //let profilePictureImageView = UIImage()
                        let image = UIImage(data: data!)
                        
                        //set the image view
                        DispatchQueue.main.async {
                            self.profilePictureImageView.image = image
                        }
                        
                    }
                    
                }
                
                dataTask.resume()  
            }
            }
        }
}

I dont understand what I am doing wrong and why the image is not showing up if anyone can explain this to me and give me an example with code that would be amazing, explain it as though you are explaining it to a kid in grade 5

Upvotes: 0

Views: 195

Answers (1)

Coder
Coder

Reputation: 553

A quick way to get Image from Firebase and assigning it to an ImageView can be done easily in these Steps.

Function to Get PhotoUrl

//Function to get photo of loggedin User
func getUrl(Completion:@escaping((String)->())) {

    let userID = Auth.auth().currentuser?.uid
    let db = Firestore.firestore().collection("photos").document(userID)
    db.getDocument { (docSnapshot, error) in
        if error != nil {
            return
        } else {
            guard let snapshot = docSnapshot, snapshot.exists else {return}
            guard let data = snapshot.data() else {return}
            let imageUrl = data["photoUrl"] as! String
            completion(imageUrl)
            
        }
    }
}

To download image and assign it to image view

//Call this function in VC where your `ImageView` is
func getImage(Url:String){

     DispatchQueue.global().async {

         let url = URL(string: Url)
         if let data = try? Data(contentsOf: url!) {

            DispatchQueue.main.async {

                  self.profilePictureImageView.image = UIImage(data: data)

                    }
                }
            }
        }
    }
 

Call these inside viewDidLoad like this:

getUrl{(url) in
 getImage(Url:url)
} 

Upvotes: 1

Related Questions