iOS Swift - PHPhotoLibrary无法完成操作。 (可可错误-1。)

时间:2018-04-27 14:23:45

标签: avfoundation swift4 ios11 photosframework xcode9.2

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

导致PHPhotoLibrary错误的原因“尝试保存视频文件时无法完成操作。(Cocoa error -1。)”

如果我像这样修改图像,

会发生:

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

我正在使用此解决方案添加文字:How do I add text to an image in 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)")
                }
            }

0 个答案:

没有答案