Reputation: 522
I am getting a weird issue with my snapshot where the username and email are being fetched but my snapshot returns nil for a profile picture.
func displayUserInformation() {
let uid = Auth.auth().currentUser?.uid
Database.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
self.username.text! = (dictionary["username"] as? String)!
self.email.text! = (dictionary["email"] as? String)!
let profileImageUrl = (dictionary["photoUrl"] as? String)!
let url = URL(string: profileImageUrl)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async {
self.profilePicture.image? = UIImage(data: data!)!
print(data!)
}
}).resume()
print(profileImageUrl)
print(snapshot)
}
}, withCancel: nil)
}
The snapshot is working and the profileUrl DOES show the data so I don't know what might be the problem. Here's what the print(profileImageUrl) shows and the snapshot
https://firebasestorage.googleapis.com/v0/b/gastet-4cfd2.appspot.com/o/profileImages%2F031F0B9F-AA41-4C16-8446-CD07893F2CA7.jpg?alt=media&token=c0e07615-8166-40e7-8d92-22bb8fbc8c8e
Snap (wL40cuYrGAVNdCVvCGUhKsD64RH2) {
email = "[email protected]";
photoUrl = "https://firebasestorage.googleapis.com/v0/b/gastet-4cfd2.appspot.com/o/profileImages%2F031F0B9F-AA41-4C16-8446-CD07893F2CA7.jpg?alt=media&token=c0e07615-8166-40e7-8d92-22bb8fbc8c8e";
username = ximeft29;
}
Upvotes: 0
Views: 170
Reputation: 11
I've duplicated your example in a sample project and have successfully been able to get it to asynchronously fetch the picture from the URL.
I've also rewritten the function to handle unwrapping the data a bit more gracefully. Any questions feel free to ask!
func displayUserInformation() {
if let currentUser = Auth.auth().currentUser {
Database.database().reference().child("users").child(currentUser.uid).observeSingleEvent(of: .value) { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject],
let username = dictionary["username"] as? String,
let email = dictionary["email"] as? String,
let urlString = dictionary["photoUrl"] as? String,
let url = URL(string: urlString) {
self.username.text = username // Set the username
self.email.text = email // Set the email
/*
* Fetch the image asyncronously
*/
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let error = error {
print("There was an error fetching the image from the url: \n", error)
}
if let data = data, let profilePicture = UIImage(data: data) {
DispatchQueue.main.async() {
self.profilePicture.image = profilePicture // Set the profile picture
}
} else {
print("Something is wrong with the image data")
}
}).resume()
}
}
}
}
Upvotes: 1