保存到用户照片库无声地失败

Rub*_*Jr. 2 uiimage ios swift

我试图使用以下代码将图像保存到iPhone上的用户相机胶卷:

UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)

但尽管没有崩溃或出错,但它失败了.我确保图像是有效的(不是零)UIImage,它确实如此.那么我尝试实现完成处理程序,如下所示:

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

// ....

@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if error != nil {
        print("ERROR! ", error!.localizedDescription)
    }
}
Run Code Online (Sandbox Code Playgroud)

但这仍然没有给我一个错误.最后,我尝试在模拟器上运行.这给了我以下错误:

Connection to assetsd was interrupted or assetsd died

Error! Write failed

是什么原因导致失败?

Rub*_*Jr. 7

我发现这个链接说,为了运行UIImageWriteToSavedPhotosAlbum,UIImage"必须是CGImage支持的".因此,为了解决这个问题,我编写了以下代码将我的UIImage转换为CIImage,然后转换为CGImage,然后返回到UIImage:

let ciImage = self.image!.ciImage
let context = CIContext()
let cgImage = context.createCGImage(ciImage!, from: ciImage!.extent)
let uiImage = UIImage(cgImage: cgImage!)

UIImageWriteToSavedPhotosAlbum(uiImage, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
Run Code Online (Sandbox Code Playgroud)

这终于工作并按预期保存到相机胶卷!

  • 这是正确的答案.我遇到过这个问题.根据之前的CG + CI经验,我预计它与CI-Backed和CG-Backed有关. (2认同)