Reputation: 79
I am new to coding and firebase. I was able to get my image pickers to recall a photo but when the user updates it with an image picker, it causes the app to crash but it's able to update in my firebase database and firebase storage with the new photo.
Heres the code and the error message after updating the photo.
func loadProfileImage() {
Database.database().reference().child("users").child(Auth.auth().currentUser!.uid).child("profileImageUrl").observe(.value, with: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value as! String
// Create a storage reference from the URL
let storageRefPF = Storage.storage().reference(forURL: downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRefPF.getData(maxSize: 1 * 1024 * 1024) { (data,error) -> Void in
// Create a UIImage, add it to the array
self.ProfileImageF.image = UIImage(data: data!)
print(snapshot)
//print(PIUvalue as Any)
}
})
}
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
I could really use the help.
Upvotes: 3
Views: 104
Reputation: 1238
Reason for crash:
Your app is crashing because you are force unwrapping data
in completion block. Force unwrapping nil
value will crash your application.
More on this: https://www.hackingwithswift.com/sixty/10/4/force-unwrapping & https://developer.apple.com/documentation/swift/optional
Fix:
Replace
self.ProfileImageF.image = UIImage(data: data!)
With
if let imgData = data {
self.ProfileImageF.image = UIImage(data: imgData)
}
This will fix your crash. If data
is still nil
and image doesn't show, I would recommend you to check firebase storage rules and make sure you have correct permissions.
Upvotes: 1