【问题标题】:How to write GIF image from url to documents directory如何将 GIF 图像从 url 写入文档目录
【发布时间】:2017-08-21 08:01:22
【问题描述】:

我有一个 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

有什么解决办法吗?

【问题讨论】:

  • 您不应使用UIImagePNGRepresentationUIImageJPEGRepresentation。只需保存数据。喜欢 Baig 的回答
  • 这只是通过下载数据写入。

标签: ios swift swift3


【解决方案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)

【讨论】:

  • 我可以知道选项在写作时原子的用途是什么
  • atomically: true 表示将数据写入备份文件,然后——假设没有错误发生——备份文件被重命名为 path 指定的名称;否则,数据直接写入路径。
【解决方案2】:

检查你应该下载

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!")
                        }
                    }
                }
            }
        }
    }

【讨论】:

  • PHPhotoLibrary有什么用
  • 导入照片以保存在库中
猜你喜欢
  • 2012-04-14
  • 2012-07-03
  • 2018-02-23
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 2012-10-26
相关资源
最近更新 更多