Refer the code here -> swift-create-a-gif-from-images-and-turn-it-into-nsdata
The above code is used for OS X, so I adjusted it a little bit.
Import ImageIO
and MobileCoreServices
func createGIF(with images: [UIImage], name: URL, loopCount: Int = 0, frameDelay: Double) {
let destinationURL = name
let destinationGIF = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypeGIF, images.count, nil)!
// This dictionary controls the delay between frames
// If you don't specify this, CGImage will apply a default delay
let properties = [
(kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): frameDelay]
]
for img in images {
// Convert an UIImage to CGImage, fitting within the specified rect
let cgImage = img.cgImage
// Add the frame to the GIF image
CGImageDestinationAddImage(destinationGIF, cgImage!, properties as CFDictionary?)
}
// Write the GIF file to disk
CGImageDestinationFinalize(destinationGIF)
}
Use it in this way:
let documentsURL = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first
let path = documentsURL!.appendingPathComponent("1.gif")
createGIF(with: images, name: path, frameDelay: 0.1)
// you can check the path and open it in Finder, then you can see the file
print(path)
I also made a demo on github -> saveImagesAsGif