Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Hello below is my code I do not understand when my friend does it on his Xcode there is no problem but when I do it I get an error can someone help:

func saveFIRData(){

    self.uploadImage(self.myimageView.image!) { url in
        
        self.saveImage(name: self.txtText.text!, profileURL: url!) { success in
            if success != nil{
                print("Yeah Yes")
            } else{
    
    }
    
}

}

}

Don't use force unwraps.

guard let image = self.myimageView.image else { return }

self.uploadImage(image) { url in
  guard let text = self.txtText, let url = url else { return }

  self.saveImage(name: text, profileURL: url) { success in
     guard let success = success else {
       print("Something went wrong!")
       return
     }
      
     print("Save image succeeded!")
}

There is still an error it says:

Cannot convert value of type 'UITextField' to expected argument type 'String'

the line that is red is : self.saveImage(name: text, profileURL: url) { success in

Have you thought about what that error might mean?

What changes to your code do you think might fix it?

2 Likes

My bad, I thought txtText was String?. It's always a good idea to name your variables more descriptively, i.e. in this case, instead of txtText, call it textLabel.

Cannot convert value of type 'UITextField' to expected argument type 'String'

The error here is pretty self-explanatory. You're passing a UITextField to something that expects a String. Since txtText is a UITextField, you need to get the text from it and pass that.

So,

guard let textField = self.txtText, let url = url else { return }
self.saveImage(name: textField.text, profileURL: url) { success in ...}

Hard to tell without the full code. Have you set Photos Library usage in Info.plist? Implemented the func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){} delegate function from UIImagePickerControllerDelegate?

Terms of Service

Privacy Policy

Cookie Policy