I am making a QR Code
image form using the following code:
func createQRFromString(str: String) -> CIImage? { let stringData = str.dataUsingEncoding(NSUTF8StringEncoding) let filter = CIFilter(name: "CIQRCodeGenerator") filter?.setValue(stringData, forKey: "inputMessage") filter?.setValue("H", forKey: "inputCorrectionLevel") return filter?.outputImage }
And then I add to UIImageView
Like this:
if let img = createQRFromString(strQRData) { let somImage = UIImage(CIImage: img, scale: 1.0, orientation: UIImageOrientation.Down) imgviewQRcode.image = somImage }
Now I need to save this in a JPEG
or PNG
file. But when I do this, my application crashes:
@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 }
Crash point
UIImageJPEGRepresentation(image, 1.0)!.writeToFile(path, atomically: true)
Cause
fatal error: unexpectedly found nil while unwrapping an Optional value
Debugging tests:

source share