David
David

Reputation: 3

Unable to load the UIImageView and UILabel immediately with the data from Firebase in Swift

I have a view controller called ProfileViewController and it contains a UIImageView for displaying the user avatar and a UILabel for displaying the username. However, it takes a while to show the avatar and username. If I go to other view controller and reopen it again, it actually can show them immediately. Also, I have tried to print out the username and avatar url and I can receive the value from Firebase instantly as well.

Here is the code:

func setUp(){

    //load avatar and other informations
    databaseRef.child("profiles").child(Auth.auth().currentUser!.uid).child("information").observeSingleEvent(of: .value, with: {(snapshot) in

        let value = snapshot.value as? NSDictionary
        self.username.text = value?["username"] as? String

        if let avatarURL = value?["avatar"] as? String {

            if let url = URL(string: avatarURL){
                let task = URLSession.shared.dataTask(with: url){
                    (data, response, error) in
                    if let data = data{
                        DispatchQueue.main.async {
                            self.avatar.image = UIImage(data: data)
                        }
                    }
                }
                task.resume()
            }
        }

    })

}

Upvotes: 0

Views: 37

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100533

There is no way to optimize this , as you have nested needed asynchronous calls , what you can change is to use SDWebImage to cache the image for upcoming visits to that vc

Upvotes: 1

Related Questions