NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Silent failure of UIImageWriteToSavedPhotosAlbum

Forums > Swift

Hi - I'm trying to make use of UIImageWriteToSavedPhotosAlbum to save QRCode images to the camera roll as part of a larger application. I'm using the following code:

func generateQRCode(from string: String) -> UIImage? {
    let data = string.data(using: String.Encoding.ascii)

    if let filter = CIFilter(name: "CIQRCodeGenerator") {
        filter.setValue(data, forKey: "inputMessage")
        let transform = CGAffineTransform(scaleX: 5, y: 5)

        if let output = filter.outputImage?.transformed(by: transform) {
            return UIImage(ciImage: output)
        }
    }

    return nil
}

@IBAction func CreateQRCode(_ sender: Any) {
    QRCode = UUID().uuidString;
    let path = QRCode

    if let image = generateQRCode(from: path) {

        UIImageWriteToSavedPhotosAlbum(image, self, #selector(handleQRCodeSaved(_:didFinishSavingWithError:contextInfo:)), nil)

        print("Generated QRCode link: \(path)")
    }
}

@objc func handleQRCodeSaved(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        print( error.localizedDescription )
    } else {
        print("Saved!")
    }
}

I've add "Privacy - Photo Library Additions Usage Description", and permission is handled correctly the moment this function chain is called.

I get the following output:

Generated QRCode link: 0FEB83CE-C6BC-4E4A-A1F9-02E732DCD9F4

Saved!

And no image... nothing in the camera roll. Nothing in the photo library. Anyone have any ideas about what I might be doing wrong? FYI - stopping in the debugger and inspecting the image shows a lovely QRCode block, just as expected.

   

I found it's because the qrcode image is ciimage. if you want to save ciimage to camera roll, it will get an error ( error code = -1), so you need to convert ciimage to cgimage first than you can save to camera roll.

if let output = filter.outputImage?.transformed(by: transform) {
    let context = CIContext()
    guard let cgImage = context.createCGImage(output, from: output.extent) else { return nil }
    return UIImage(cgImage: cgImage)
}

   

Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.