Grimxn Grimxn - 3 months ago 31
Swift Question

CGImageDestinationCreateWithData constants in iOS

I have the following code which turns a

CGImage
into
NSData
:

import Foundation
import CoreGraphics
import ImageIO
// ... snip ...
let data = NSMutableData()
if let dest = CGImageDestinationCreateWithData(data, kUTTypePNG, 1, nil), let image = self.backgroundImage {
CGImageDestinationAddImage(dest, image, nil)
if CGImageDestinationFinalize(dest) {
return data as Data
}
}
return nil


The code compiles fine in Mac-OS, but
kUTTypePNG
is undefined in iOS. The actual value of the constant is
"public.png"
, and obviously, replacing the constant with that value allows iOS to compile the code fine.

But avoiding magic strings/numbers is the reason we use constants in the first place - is there an alternative constant in Swift-iOS?

Answer

From Mobile Core Services Framework in the "iOS Technology Overview":

The Mobile Core Services framework (MobileCoreServices.framework) defines the low-level types used in uniform type identifiers (UTIs).

For more information about the types defined by this framework, see Uniform Type Identifiers Reference.

So

import MobileCoreServices

makes

public let kUTTypePNG: CFString

and other UTI constants available to your code.