I am trying to generate a gif file from array of images using following code snippet - Facing a crash with iOS15. For iOS15 -> Updating the deprecated "kUTTypeGIF" to "UTType.gif.identifier" doesn't prevent the crash.
func createGif(fromImages images:[UIImage], withSize size: CGSize) -> CFURL? {
guard !images.isEmpty else{
return nil
}
let fileProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] as CFDictionary
let frameProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: 0.125]] as CFDictionary
//gets the url
let documentsDirectoryURL: URL? = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
//add the filename
let fileURL: URL? = documentsDirectoryURL?.appendingPathComponent("animatedImage.gif")
if let url = fileURL as CFURL? {
//iOS15 -> Updating to UTType.gif.identifier
if let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, images.count, nil) {
CGImageDestinationSetProperties(destination, fileProperties)
for image in images {
autoreleasepool {
let modifiedImage = image.scaled(to: size, scalingMode: .aspectFill)
if let cgImage = modifiedImage.cgImage {
CGImageDestinationAddImage(destination, cgImage, frameProperties)
}
}
}
if !CGImageDestinationFinalize(destination) {
print("Failed to finalize the image destination")
return nil
}else{
//converted to gif sucsessfully
return url
}
}
}
//something went wrong
return nil
}
The memory allocation with CGImageDestinationAddImage increases exponentially with each iteration and finally lands in applicationDidReceiveMemoryWarning which terminates the App. The autoreleasepool added within for loop fails to releases the allocated memory leading to the crash. Any thoughts to resolve the issue are much appreciated. Thanks~