能否在Swift中使用UIImageWriteToSavedPhotosAlbum保存动画gif?

能否在Swift中使用UIImageWriteToSavedPhotosAlbum保存动画gif?,swift,uiimage,animated-gif,Swift,Uiimage,Animated Gif,我有一个函数,可以从UIImage数组中创建gif。我可以检查一下数量,是32张图片。我认为我做错了,我正在将URL数据转换回UIImage,它只保存第一帧。我宁愿直接从URL保存图像,但除了从视频中保存AVAsset外,我不熟悉任何方法 func createGIF(with images: [UIImage], loopCount: Int = 0, frameDelay: Double) { let fileProperties = [kCGImagePropertyGIFDict

我有一个函数,可以从UIImage数组中创建gif。我可以检查一下数量,是32张图片。我认为我做错了,我正在将URL数据转换回UIImage,它只保存第一帧。我宁愿直接从URL保存图像,但除了从视频中保存AVAsset外,我不熟悉任何方法

func createGIF(with images: [UIImage], loopCount: Int = 0, frameDelay: Double) {
    let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: loopCount]]
    let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: frameDelay]]

    let documentsDirectory = NSTemporaryDirectory()
    let url = NSURL(fileURLWithPath: documentsDirectory).appendingPathComponent("myAnimatedGIF.gif")

    let destination = CGImageDestinationCreateWithURL(url! as CFURL, kUTTypeGIF, Int(images.count), nil)
    CGImageDestinationSetProperties(destination!, fileProperties as CFDictionary)

    print(images.count)
    for i in 0..<images.count {
        CGImageDestinationAddImage(destination!, images[i].cgImage!, frameProperties as CFDictionary)
    }

    if CGImageDestinationFinalize(destination!) {           
        let data = try? Data(contentsOf: url!)

        if data != nil {
            print("saved gif")
            let image = UIImage(data: data!)
            UIImageWriteToSavedPhotosAlbum(image!, self, #selector(addImageToLibrary(_:didFinishSavingWithError:contextInfo:)), nil)

        }


    } else {
        print("failed")
    }
}

但是我得到了错误“不明确地使用'init(contentsOfURL:)”,我不知道在Swift 4中这样做的方法。

Swift3和更高版本您应该使用
Data
initializer
Data(contentsOfURL)
而不是
NSData
。但要从非本地资源URL加载数据,您应该使用
URLSession
dataTask(with:URL)
方法异步下载数据。顺便说一句,这同样适用于NSURL。您应该删除NS前缀,并使用
URL
初始值设定项。嘿!你找到解决办法了吗?自从我发布这篇文章以来,很多事情都发生了变化,但请查看ChanWarde的CustomPhotoAlbum:
let image = NSData(contentsOfURL: url!)

ALAssetsLibrary().writeImageDataToSavedPhotosAlbum(image, metadata: nil, completionBlock: { (assetURL: NSURL!, error: NSError!) -> Void in
                    print(assetURL)
                })