UIImageWriteToSavedPhotosAlbum不工作

时间:2018-01-31 06:06:43

标签: ios swift uiimage qr-code ciimage

我正在从字符串生成条形码,然后尝试将此图像保存到iPhone照片库。这是我的代码:

@IBOutlet weak var uuidLabel: UILabel!
@IBOutlet weak var barcodeDisplay: UIImageView!

@IBAction func generateBarcode(_ sender: Any) {
    barcodeDisplay.image = generateBarcodeFromString(string: uuidLabel.text!)
    UIImageWriteToSavedPhotosAlbum(barcodeDisplay.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}

@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }
}

func generateBarcodeFromString(string:String)->UIImage? {
    let data = string.data(using: String.Encoding.ascii)
    if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
        filter.setValue(data, forKey: "inputMessage")
        let transform = CGAffineTransform(scaleX: 1, y: 1)
        if let output = filter.outputImage?.transformed(by: transform) {
            return UIImage(ciImage: output)
        }
    }
    return nil
}

当我运行此应用程序时,它会生成条形码并显示在视图控制器上。当我尝试将此图像保存到iPhone照片库时,选择器会显示“您的图像已保存到照片中”。但图像未保存到iPhone照片库中。

之后,当我尝试通过以下方式将此图像转换为NSData时:

let data = UIImagePNGRepresentation(barcodeDisplay.image!) as NSData?

它的回报为零。这背后的问题是什么?

1 个答案:

答案 0 :(得分:4)

问题是QRCode是CIImage所以我们需要将它转换为UIImage才能保存到相册

<强> QRCodeGenerator.swift

import Foundation
import UIKit


class QRCodeGenerator {

    class func generateQRCodeFromString(_ strQR:String) -> CIImage {
        let dataString = strQR.data(using: String.Encoding.isoLatin1)

        let qrFilter = CIFilter(name:"CIQRCodeGenerator")
        qrFilter?.setValue(dataString, forKey: "inputMessage")
        return (qrFilter?.outputImage)!
    }



    class func convert(_ cmage:CIImage) -> UIImage
    {
        let context:CIContext = CIContext.init(options: nil)
        let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!
        let image:UIImage = UIImage.init(cgImage: cgImage)
        return image
    }

}

<强> QRCodeVC

import UIKit

class QRCodeVC: UIViewController {

    @IBOutlet weak var imgView: UIImageView!
    var imgQrCode: UIImage!

  override func viewDidLoad() {
        super.viewDidLoad()
        self.generateQRCodeFromString()

}

    func generateQRCodeFromString() -> Void{

        let id:String = "QRCODE TEXT IN HERE"

        let ciImageFromQRCode = QRCodeGenerator.generateQRCodeFromString(id)

        // Scale according to imgViewQRCode. So, image is not blurred.
        let scaleX = (imgView.frame.size.width / ciImageFromQRCode.extent.size.width)
        let scaleY = (imgView.frame.size.height / ciImageFromQRCode.extent.size.height)

        let imgTransformed = ciImageFromQRCode.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY))
        self.imgView.image = QRCodeGenerator.convert(imgTransformed)
        self.imgQrCode = QRCodeGenerator.convert(imgTransformed)

    }


    @IBAction func actionSaveQRCode(_ sender: Any) {

        UIImageWriteToSavedPhotosAlbum( self.imgView.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)


    }

    @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            // we got back an error!
            let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .default))
            present(ac, animated: true)
        } else {
            let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .default))
            present(ac, animated: true)
        }
    }

    @IBAction func actionShare(_ sender: Any) {

        // image to share

        let myShare = "My beautiful photo! <3 <3"
        let image =  self.imgView.image!

        // set up activity view controller
        let imageToShare = [ image , myShare] as [AnyObject] // [ image! ]

        print("imageToShare \(imageToShare)")

        let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        self.present(activityViewController, animated: true, completion: nil)

    }


}