Reputation: 21
I try to upload an Image to the Firebase Database, but every time I select a Picture and try to upload it, I get an error saying Thread+1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
This error appeared after I updated firebase...
func save() {
let newPostKey = ref.key
// save jobImage
if let imageData = jobImage?.jpegData(compressionQuality: 0.5) {
let storage = Storage.storage().reference().child("jobImages/\(newPostKey!)")
storage.putData(imageData, metadata: nil) { (metadata, error) in
if error != nil{
print(error!)
} else {
storage.downloadURL(completion: { (URL, error) in
if error != nil{
print(error!)
return
}
if URL != nil{
let postDictionary = [
"imageDownloadURL" : self.downloadURL!, //-> ERROR (Removing the '!' doesn't give any error, but then also no picture gets uploaded...)
"text" : self.text,
] as [String : Any]
self.ref.setValue(postDictionary)
}
})
}
}
}
}
I select the picture like this:
let newJob = Job(text: jobTextView.text, jobImage: takenImage!)
newJob.save()
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
self.dismiss(animated: true) { [weak self] in
guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
//Setting image to your image view
self!.takenImage = image
self!.jobImage.image = self!.takenImage //-> The imageVIew gets filled with the takenImage, so I guess that nothings wrong there
self!.changeImage.isHidden = false
self!.addImage.isHidden = true
}
}
EDIT:
var jobImage: UIImage?
var downloadURL: String?
var jobImage: UIImage?
init(text: String? = nil, jobImage: UIImage? = nil) {
self.text = text!
self.jobImage = jobImage
ref = Database.database().reference().child("jobs").childByAutoId()
}
init(snapshot: DataSnapshot){
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
text = value["text"] as! String
downloadURL = value["imageDownloadURL"] as? String
}
}
Upvotes: 0
Views: 70
Reputation: 599051
You're not setting self.downloadURL
anywhere, which means that it's nil
and leads to the error when you try to unwrap it.
You can either set the self.downloadURL
inside the callback:
storage.downloadURL(completion: { (URL, error) in
if error != nil{
print(error!)
return
}
if URL != nil{
self.downloadURL = URL
let postDictionary = [
"imageDownloadURL" : self.downloadURL!,
"text" : self.text,
] as [String : Any]
self.ref.setValue(postDictionary)
}
})
Or you can directly pass the URL
parameter into the database call:
"imageDownloadURL" : URL!
Upvotes: 2