Unable to convert CIImage to UIImage in Swift 3.0 : <p>I am making image form <code>QR Code</code> by using following code:</p>

<pre><code>  func createQRFromString(str: String) -&gt; CIImage? {
        let stringData = str.dataUsingEncoding(NSUTF8StringEncoding)

        let filter = CIFilter(name: "CIQRCodeGenerator")

        filter?.setValue(stringData, forKey: "inputMessage")

        filter?.setValue("H", forKey: "inputCorrectionLevel")

        return filter?.outputImage
    }
</code></pre>

<p>And Then I am adding to <code>UIImageView</code> Like this:</p>

<pre><code>    if let img = createQRFromString(strQRData) {
        let somImage = UIImage(CIImage: img, scale: 1.0, orientation: UIImageOrientation.Down)
        imgviewQRcode.image = somImage
    }
</code></pre>

<p>Now I need to save this to a <code>JPEG</code> or <code>PNG</code> file. But when I am doing so my app crashes:</p>

<pre><code>    @IBAction func btnSave(sender: AnyObject) {

    //        // Define the specific path, image name
    let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    // create a name for your image
    let fileURL = documentsDirectoryURL.URLByAppendingPathComponent("image.jpg")

    if let image = imgviewQRcode.image // imgviewQRcode is UIImageView
    {

        if let path = fileURL?.path
        {
            if !NSFileManager.defaultManager().fileExistsAtPath(fileURL!.path!)
            {
                if UIImageJPEGRepresentation(image, 1.0)!.writeToFile(path, atomically: true)
                {
                    print("file saved")
                }

            }//Checking existing file

        }//Checking path

    }//CHecking image

}
</code></pre>

<p><strong>Crash Point</strong></p>

<pre><code>  UIImageJPEGRepresentation(image, 1.0)!.writeToFile(path, atomically: true)
</code></pre>

<p><strong>Reason</strong></p>

<pre><code>fatal error: unexpectedly found nil while unwrapping an Optional value
</code></pre>

<p>Debug Tests:</p>

<p><a href="https://i.stack.imgur.com/8fzGa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8fzGa.png" alt="enter image description here"></a></p>
