CGImageDestinationCreateWithURL的问题

时间:2017-04-04 18:14:37

标签: 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(字符串:路径)而不是URL(fileURLWithPath :)时,我收到以下错误:

  

:CGDataConsumer(url_close):写入失败。

关于可能发生的事情的任何想法?我应该使用哪条路径?

1 个答案:

答案 0 :(得分:2)

我会回答这个问题以防其他人解决这个问题。经过一些研究并使用评论信息,我找到了解决方案。我最终使用了:

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

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