我知道这个...... 我的应用崩溃了,因为它从Firebase中找到了一个零值。虽然Xcode中有一个默认图像,但新用户在firebase中还没有数据,因此解开nil值会导致不可避免的崩溃。如何在新用户选择其中一个之前显示默认配置文件图像?
func setupProfile(){
profile_image.layer.cornerRadius = profile_image.frame.size.width/2
profile_image.clipsToBounds = true
if let uid = Auth.auth().currentUser?.uid{
databaseRef.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let dict = snapshot.value as? [String: AnyObject]
{
self.usernameLabel.text = dict["username"] as? String
if let profileImageURL = dict["pic"] 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.profile_image?.image = UIImage(data: data!)
}
}).resume()
}
}
})
}
}
答案 0 :(得分:0)
你尝试过使用方法
吗?if snapshot.exists(){
/// Code when snapshot returns a Value
}
else{
/// Snapshot has no value
/// Here is the crash point
/// dont run other operations
}
第二个选项
databaseRef.child("Events").observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
if snapshot.hasChild(/// Comparison value if you have , Like checking for a Value to verify snapshot is not empty)
{
/// Value found /// Run operations
}
else{
/// Value not found
}
})