UIImageWriteToSavedPhotosAlbum 不工作

UIImageWriteToSavedPhotosAlbum not working

我正在从字符串生成条形码,然后尝试将此图像保存到 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 照片库时,选择器显示,"Your image has been saved to your photos." 但图像未保存到 iPhone 照片库。

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

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

return 为零。这背后的问题是什么?

Swift version: 5.2

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

QRCodeGenerator.swift

import UIKit

final class QrCodeGenerator {
    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) // Scale according to imgView
            if let output = filter.outputImage?.transformed(by: transform) {
                return convert(output)
            }
        }
        return nil
    }

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

ImageSaver.swift

import UIKit

final class ImageSaver: NSObject {
    func writeToPhotoAlbum(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveError), nil)
    }

    @objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            print("error: \(error.localizedDescription)")
        } else {
            print("Save completed!")
        }
    }
}

QrCodeViewController

import UIKit

class QrCodeViewController: UIViewController {
    @IBOutlet weak var qrCodeImageView: UIImageView!
    private let qrCodeGenerator = QrCodeGenerator()
    private let imageSaver = ImageSaver()

    init() {
        super.init(nibName: "QrCodeViewController", bundle: nil)
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save Photo", style: .plain, target: self, action: #selector(addTapped))
        guard let image = qrCodeGenerator.generateQRCode(from: "mock") else { return }
        qrCodeImageView.image = image
    }

    @objc func addTapped() {
        guard let inputImage = QrCodeGenerator().generateQRCode(from: "mock") else { assertionFailure("null image"); return }
        imageSaver.writeToPhotoAlbum(image: inputImage)
    }

}

为了让应用程序能够将照片写入(添加)到设备照片库中,我们必须将 NSPhotoLibraryAddUsageDescription 添加到应用程序的 plist 文件中:

<key>NSPhotoLibraryAddUsageDescription</key>
<string>Our application needs permission to write photos...</string>