This code to write UIImage data as heic works in iOS simulator with iOS < 17.5
import AVFoundation
import UIKit
extension UIImage {
public var heic: Data? { heic() }
public func heic(compressionQuality: CGFloat = 1) -> Data? {
let mutableData = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(mutableData, AVFileType.heic as CFString, 1, nil),
let cgImage = cgImage else {
return nil
}
let options: NSDictionary = [
kCGImageDestinationLossyCompressionQuality: compressionQuality,
kCGImagePropertyOrientation: cgImageOrientation.rawValue,
]
CGImageDestinationAddImage(destination, cgImage, options)
guard CGImageDestinationFinalize(destination) else { return nil }
return mutableData as Data
}
public var isHeicSupported: Bool {
(CGImageDestinationCopyTypeIdentifiers() as! [String]).contains("public.heic")
}
var cgImageOrientation: CGImagePropertyOrientation { .init(imageOrientation) }
}
extension CGImagePropertyOrientation {
init(_ uiOrientation: UIImage.Orientation) {
switch uiOrientation {
case .up: self = .up
case .upMirrored: self = .upMirrored
case .down: self = .down
case .downMirrored: self = .downMirrored
case .left: self = .left
case .leftMirrored: self = .leftMirrored
case .right: self = .right
case .rightMirrored: self = .rightMirrored
@unknown default:
fatalError()
}
}
}
But with iOS 17.5 simulator it seems to be broken. The call of CGImageDestinationFinalize writes this error into the console:
writeImageAtIndex:962: *** CMPhotoCompressionSessionAddImage: err = kCMPhotoError_UnsupportedOperation [-16994] (codec: 'hvc1')
On physical devices it still seems to work.
Is there any known workaround for the iOS simulator?