I'm trying to save a video file to photo library. I got the following code snippet working, but I'm getting weird cocoa error -1 when trying to save a video created using UIImages with text added programmatically.
What is causing PHPhotoLibrary error "The operation couldn’t be completed. (Cocoa error -1.)" when trying to save a video file?
happens if I modify the images like this:
let midX = image.size.width / 2.0
let imageWithText = image.textToImage(drawText: "Added text", inImage: image, atPoint: CGPoint(x: midX, y: 100))
I'm using this solution to add text: 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!
}
This code works as long as the image has not been altered by adding text:
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)")
}
}