Antiokhos Antiokhos - 1 year ago 108
Swift Question

How I can dowload GIF image in swift

I am developing some tumblr client. And i want to download all photos in dashboard and save them to documentDirectory. Some of them is jpg some are gif. I have successfully download jpg images with this code:

do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(fname)
if let pngImageData = UIImagePNGRepresentation(myImage!) {
try pngImageData.write(to: fileURL, options: .atomic)
print(fname + " - saved")
} catch {print(fname + " - not saved") }

myImage is the image which is downloaded from URL. This code is work for jpg images but not good for gifs.

And lastly i read these files with this:

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let filePath = documentsURL.appendingPathComponent(fname).path
if FileManager.default.fileExists(atPath: filePath) {
return UIImage(contentsOfFile: filePath)!

It's work for jpg but not for gifs. when i try this writing/reading codes on gifs images, i got just image not animation.

Can you show me the way pls with an example will be awesome.

Thank you.

Answer Source

Actually your first code is not working correctly either.

What you are receiving is the image. You do not need or want to translate it into some other kind of image (UIImagePNGRepresentation). Just save the data. Later, read the data directly into a UIImage.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download