我的快照出现了一个奇怪的问题,在该快照中,用户名和电子邮件已被提取,但是对于个人资料照片,快照返回nil。
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)
}
快照正在运行,profileUrl确实显示了数据,所以我不知道可能是什么问题。这是print(profileImageUrl)显示的内容和快照
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 = "ximeft29@gmail.com";
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;
}
答案 0 :(得分:1)
我已经在一个示例项目中复制了您的示例,并成功地获得了它以从URL异步获取图片。
我还重写了该函数,以更优雅地处理数据展开。任何问题都可以问!
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()
}
}
}
}