我已经了解到,根据文档,自从iOS 9以来,Image IO Framework已经在语法上发生了变化,但是我已经完成了我的研究,并且以下代码似乎是正确的。我必须遵守下列程序;一个过程拍摄图像并将这些图像作为gif写入应用程序的文档文件夹。我可以确认这是有效的,因为如果我使用iTunes转到应用程序的文档文件夹,我可以查看实际的gif文件。尽管如此,在我尝试从同一个文件中读取的第二个过程中,抛出一个错误,指出该路径上的文件不存在。我已经发布了以下代码。
class GifManager {
private func getDocumentsDirectory() -> URL? {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
}
public func generateGif(photos: [UIImage], filename: String) -> Bool {
if let docsDirectory = getDocumentsDirectory() {
let url = docsDirectory.appendingPathComponent(filename)
let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]]
let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: 0.125]]
if let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, photos.count, nil) {
CGImageDestinationSetProperties(destination, fileProperties as CFDictionary?)
for photo in photos {
CGImageDestinationAddImage(destination, photo.cgImage!, gifProperties as CFDictionary?)
}
return CGImageDestinationFinalize(destination)
}
}
return false
}
public func saveGifToCameraRoll(filename: String) {
if let docsDirectory = getDocumentsDirectory() {
let fileUrl: URL = docsDirectory.appendingPathComponent(filename)
do {
let data = try Data(contentsOf: fileUrl)
if let _ = UIImage(data: data) {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: fileUrl)
}, completionHandler: {completed, error in
if error != nil {
print("error")
} else if completed {
print("completed")
} else {
print("not completed")
}
})
}
} catch let error {
print(error)
}
}
}