0

I am making an app which generates QR-code and saves it to the camera roll, but calling the saving function causes app crash with a fatal error: unexpectedly found nil while unwrapping an Optional value.

     @IBAction func saveTapped(_ sender: Any) {

        let imageData = UIImagePNGRepresentation(codeView.image!)
        let compressedImage = UIImage(data: imageData!)
        UIImageWriteToSavedPhotosAlbum(compressedImage!, self, nil, nil)

        let alert = UIAlertController(title: "Image Saved", message: "Your QR code is saved to CameraRoll", preferredStyle: .alert)
        let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
        alert.addAction(okayAction)
        self.present(alert, animated: true, completion: nil)


}

The error comes on line 2, on
compressedImage = UIImage(data: imageData!).

Akif
  • 59
  • 3
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Keiwan Jul 30 '17 at 11:53

1 Answers1

4

This is how I solved my problem:

     @IBAction func saveTapped(_ sender: Any) {
    UIGraphicsBeginImageContext(codeView.frame.size)
    codeView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let output = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

        UIImageWriteToSavedPhotosAlbum(output!, nil, nil, nil)

        let alert = UIAlertController(title: "Image Saved", message: "Your QR code is saved to CameraRoll", preferredStyle: .alert)
        let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
        alert.addAction(okayAction)
        self.present(alert, animated: true, completion: nil)
}
Akif
  • 59
  • 3