如何将URL中的GIF图像写入文档目录

时间:2017-08-21 08:01:23

标签: ios swift swift3

我有一个gif图片url并想将其下载到文档目录,为此我尝试使用

if let gifImageData = UIImagePNGRepresentation(image!) {
    try gifImageData.write(to: fileURL, options: .atomic)
}

以及

if let jpegImageData = UIImageJPEGRepresentation(image!, 1.0) {
    try jpegImageData.write(to: fileURL, options: .atomic)
}

但是这张图片保存为单个png / jpg图片而不是动画gif

对此有何解决方案?

2 个答案:

答案 0 :(得分:1)

问题在于你的文件名,试试这个:

//The URL to Save
let yourURL = NSURL(string: "http://somewebsite.com/somefile.gif")
//Create a URL request
let urlRequest = NSURLRequest(URL: yourURL!)
//get the data
let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)

//Get the local docs directory and append your local filename.
var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL

docURL = docURL?.URLByAppendingPathComponent( "myFileName.gif")

//Lastly, write your file to the disk.
theData?.writeToURL(docURL!, atomically: true)

答案 1 :(得分:0)

检查你应该下载

func download() {
        DispatchQueue.global(qos: .background).async {
            if let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif"),
                let urlData = NSData(contentsOf: url)
            {
                let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
                let filePath="\(documentsPath)/tempFile.gif";
                DispatchQueue.main.async {
                    urlData.write(toFile: filePath, atomically: true)
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
                    }) { completed, error in
                        if completed {
                            print("photo is saved!")
                        }
                    }
                }
            }
        }
    }