首页 > 解决方案 > iOS Swift - PHPhotoLibrary 操作无法完成。(可可错误-1。)

问题描述

我正在尝试将视频文件保存到照片库。我得到了以下代码片段,但是当我尝试保存使用 UIImages 创建的视频并以编程方式添加文本时,我得到了奇怪的可可错误 -1。

尝试保存视频文件时,是什么导致 PHPhotoLibrary 错误“操作无法完成。(Cocoa 错误 -1。)”?

如果我像这样修改图像会发生:

let midX = image.size.width / 2.0
let imageWithText = image.textToImage(drawText: "Added text", inImage: image, atPoint: CGPoint(x: midX, y: 100))

我正在使用此解决方案添加文本:如何在 iOS Swift 中向图像添加文本?

func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
    let textColor = UIColor.white
    let textFont = UIFont(name: "Helvetica Bold", size: 12)!

    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

    let textFontAttributes = [
        NSAttributedStringKey.font: textFont,
        NSAttributedStringKey.foregroundColor: textColor,
        ] as [NSAttributedStringKey : Any]
    image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))

    let rect = CGRect(origin: point, size: image.size)
    text.draw(in: rect, withAttributes: textFontAttributes)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
 }

只要图像没有通过添加文本进行更改,此代码就可以工作:

PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: fileURL)
            }) { saved, error in
                if saved {
                   print("Saved video")
                }else if error != nil
                {
                    //getting error -1 here
                    print ("error: \(error!.localizedDescription)")
                }
            }

标签: avfoundationswift4ios11photosframeworkxcode9.2

解决方案


推荐阅读