'How to use GIFs inside an iOS App without any Third Party Library in Swift 5 using UIKit?

i am currently working on a project which depends heavily on GIFs. However, I never worked with GIFs in Swift for iOS before an am pretty lost;)

The first thing I tried was to import some GIFs to my Assets.xcassets Folder. I realised that using an ImageSet for GIFs does not work.

So my first Question: How do I import GIFs into my project. And should I use only one resolution or are three the better way like for images?

Then I already checked out some Questions about presenting a GIF inside an UIImageView, programatically and via Storyboard. As I figured out this is probably best possible by using an Extension for UIImage Class. However, the Swift 4 Examples didn't work for me because of some reason;(

So my second Question: How do I use the imported GIFs inside my project and display them inside an UIImage View programatically?

Thanks a lot for your help guys in advance!



Solution 1:[1]

I also had this kind of problem to solve. I found answers in this thread helpful. Please check them out. Add animated Gif image in Iphone UIImageView

Also, I highly recommend to checkout some implementations inside FLAnimatedImage. It handles showing, playing and other functionalities you might need for GIFs in iOS.

Solution 2:[2]

If your animated gif has a constant frame time for all frames then you can easily load it from your assets catalog without third party libraries with this:

extension UIImage {
    static func animatedGif(named: String, framesPerSecond: Double = 10) -> UIImage? {
        guard let asset = NSDataAsset(name: named) else { return nil }
        return animatedGif(from: asset.data, framesPerSecond: framesPerSecond)
    }

    static func animatedGif(from data: Data, framesPerSecond: Double = 10) -> UIImage? {
        guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
        let imageCount = CGImageSourceGetCount(source)
        var images: [UIImage] = []
        for i in 0 ..< imageCount {
            if let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) {
                images.append(UIImage(cgImage: cgImage))
            }
        }
        return UIImage.animatedImage(with: images, duration: Double(images.count) / framesPerSecond)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nare Muradyan
Solution 2