I would recommend using the following code, it's much more lightweight, and compatible with ARC and non-ARC project, it adds a simple category on UIImageView:
This method loads a series of files by appending a series of numbers
to the base file name provided in the name parameter. For example, if
the name parameter had ‘image’ as its contents, this method would
attempt to load images from files with the names ‘image0’, ‘image1’
and so on all the way up to ‘image1024’. All images included in the
animated image should share the same size and scale.
Another alternative is to use a UIWebView to display the animated GIF. If the GIF is going to be fetched from a server, then this takes care of the fetching. It also works with local GIFs.
In 2021, splitting gif into individual frames is still a valid solution.
Here is the accepted answer adapted to Swift:
Split your gif into individual frames using an online service like ezygif: https://ezgif.com/split/
Make sure to export them as .png.
Create an xcassets arhcive and create an asset for each frame. Make sure that the difference is just the suffix which should be a number for each frame of the gif (i.e. animated-image-1, animaged-image-2, etc)
I'm using a single scale to make it easier.
Load it up into an image view:
final class AnimatedImage: UIImageView {
init() {
super.init(frame: .zero)
let animatedImage = UIImage.animatedImageNamed("animated-image-", duration: 0.3)
translatesAutoresizingMaskIntoConstraints = false
image = animatedImage
NSLayoutConstraint.activate([
widthAnchor.constraint(equalToConstant: 150),
heightAnchor.constraint(equalTo: widthAnchor)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}