iOS 18.2 crash on CGImageDestinationFinalize

My app reports a lot of crashes from 18.2 users.

I have been able to narrow down the issue to this line of code: CGImageDestinationFinalize(imageDestination)

The error is Thread 93: EXC_BAD_ACCESS (code=1, address=0x146318000)

But I have no idea why this suddently started to crash.

Here is the code of the function:

private func estimateSizeUsingThumbnailMethod(fromImageURL url: URL, imageSettings: ImageSettings) -> (Int, Int) {
    let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
    guard let source = CGImageSourceCreateWithURL(url as CFURL, sourceOptions),
          let imageProperties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
          let imageWidth = imageProperties[kCGImagePropertyPixelWidth] as? CGFloat,
          let imageHeight = imageProperties[kCGImagePropertyPixelHeight] as? CGFloat else {
        return (0, 0)
    }
    
    let maxImageSize = max(imageWidth, imageHeight)
    let thumbMaxSize = min(2400, maxImageSize) // Use original size if possible, but not if larger than 2400, in this case we'll extrapolate from thumbnail
    
    let downsampleOptions = [
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceThumbnailMaxPixelSize: thumbMaxSize as CFNumber,
    ] as CFDictionary

    guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, downsampleOptions) else {
        DLog("CGImage thumb creation error")
        return (0, 0)
    }
    
    let data = NSMutableData()
            
    guard let imageDestination = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil) else {
        DLog("CGImage destination creation error")
        return (0, 0)
    }

    let destinationProperties = [
        kCGImageDestinationLossyCompressionQuality: imageSettings.quality.compressionRatio() // Set jpeg compression ratio
    ] as CFDictionary

    CGImageDestinationAddImage(imageDestination, cgImage, destinationProperties)
    CGImageDestinationFinalize(imageDestination)   // <----- CRASHES HERE with EXC_BAD_ACCESS
	
	...
}

So far, I'm stuck. Any idea that could help would be greatly appreciated, as I'm scared that this crash will propagate on the official release of 18.2

Changing let thumbMaxSize = min(2400, maxImageSize)

with

let thumbMaxSize = min(1200, maxImageSize)

thus, simply reducing the image size, fixed the issue. I don't know what changed in 18.2 in that regards, but I must say that I'm happy that my use case allows for reducing the image size.

Any detail would be appreciated, in order to ensure that everything is working as it should. Thanks!

iOS 18.2 crash on CGImageDestinationFinalize
 
 
Q