display a gif in swiftui in swift

To display a GIF in SwiftUI, we need to use a UIViewRepresentable protocol to create a UIView that displays the GIF. Here’s the code to create a reusable view that displays a GIF:

main.swift
import SwiftUI
import UIKit

struct GifView: UIViewRepresentable {
    let gifName: String

    func makeUIView(context: Context) -> UIImageView {
        let imageView = UIImageView()
        let gif = UIImage.gif(name: gifName)
        imageView.image = gif
        imageView.contentMode = .scaleAspectFit
        return imageView
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
    }
}

extension UIImage {
    static func gif(name: String) -> UIImage? {
        guard let bundleURL = Bundle.main
            .url(forResource: name, withExtension: "gif") else {
            print("This image named \"\(name)\" does not exist")
            return nil
        }

        guard let imageData = try? Data(contentsOf: bundleURL) else {
            print("Cannot get data of image named \"\(name)\"")
            return nil
        }

        let source = CGImageSourceCreateWithData(imageData as CFData, nil)!
        let count = CGImageSourceGetCount(source)

        var images = [UIImage]()

        for i in 0..<count {
            guard let image = CGImageSourceCreateImageAtIndex(source, i, nil) else { continue }

            images.append(UIImage(cgImage: image))
        }

        return UIImage.animatedImage(with: images, duration: 1.0)
    }
}
1279 chars
46 lines

Then, to use the GifView in SwiftUI, simply add it to the body of a View:

main.swift
struct ContentView: View {
    var body: some View {
        GifView(gifName: "example")
    }
}
97 chars
6 lines

Replace "example" with the name of your GIF file.

gistlibby LogSnag