ios - CGImageDestinationCreateWithURL 的问题

标签 ios swift image cgimage

我正在使用 CGImageDestinationCreateWithURL 来保存 gif 图像,这是我的代码:

func gifFromImages(images: Array<UIImage>, animationTime: Double) -> String? {
        let date = Int(NSDate().timeIntervalSince1970)

        let path = Bundle.main.bundlePath + "/gifs/" + String(date) + ".gif"        

        let delay = animationTime / Double(totalFrames)

        let prep = [kCGImagePropertyGIFDictionary as String :
               [kCGImagePropertyGIFDelayTime as String : delay]] as CFDictionary

        let fileProperties = [ kCGImagePropertyGIFDictionary as String : 
                               [kCGImagePropertyGIFLoopCount as String : 0] ,
                               kCGImageMetadataShouldExcludeGPS as String: true]
                               as CFDictionary

        let url = URL(fileURLWithPath: path) as CFURL

        guard let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, 
                                images.count, nil) else {
                return nil
        }

        CGImageDestinationSetProperties(destination, fileProperties)

        for image in images {
            if let cgImage = image.cgImage {
                CGImageDestinationAddImage(destination, cgImage, prep)
            }
        }

        if CGImageDestinationFinalize(destination) {
            return path
        }

        return nil
    }

我面临的问题是,当我在模拟器上尝试此代码时,它工作正常并创建我需要的文件,但是当我在设备上运行此代码时,CGImageDestinationCreateWithURL 返回 nil。 我的第一个想法是文件的路径不正确,我在网上查看并尝试使用以下路径/网址:

let path = Bundle.main.bundlePath + "/gifs/" + String(date) + ".gif"

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!.appending("/gifs/\(String(date)).gif")

let path = NSString(string: "~/gifs/\(String(date)).gif").expandingTildeInPath

let url = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) as CFURL

当我尝试使用 URL(string: path) 而不是 URL(fileURLWithPath:) 时,出现以下错误:

: CGDataConsumer(url_close): write failed.

对可能发生的事情有什么想法吗?我应该使用哪条路径?

最佳答案

如果其他人遇到这个问题,我会回答这个问题。经过一番研究并使用评论中的信息,我找到了解决方案。我最终使用了:

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory,
           .userDomainMask, true).last?.appending("/\(String(date)).gif")

我的第一个解决方案的问题是它在文档目录和文件名之后添加了一个文件夹。

关于ios - CGImageDestinationCreateWithURL 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43214686/

相关文章:

ios - 从Xcode删除模拟器

ios - Appdelegate 问题

ios - 射弹并非来自正确的位置

html - 悬停时调整图像大小会使其他图像移动

jQuery UI 对话框向图像添加不需要的内联样式

java - 如何在 Vaadin 中循环等待?

ios - ReplayKit 初始警报选择的委托(delegate)方法是什么?

ios - 如何使用 AFnetworking 或 NSJsonserialization 发布 json 数据

ios - 暂停和恢复 ASINetworkQueue

ios - Swift Firebase 数据库覆盖