丢失firebase照片时崩溃



我知道这...我的应用程序崩溃是因为它从Firebase找到了零值。虽然XCode中有默认图像,但新用户在Firebase中尚无数据,因此拆开零值会导致不可避免的崩溃。如何显示默认配置文件映像,直到新用户选择自己的一个?

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()
                }
            }
        })
    }
}

您是否尝试过使用方法

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 
             }
})

最新更新