iOS 中的 CGImageDestinationCreateWithData 常量

CGImageDestinationCreateWithData constants in iOS

我有以下代码将 CGImage 变成 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

代码在 Mac-OS 中编译良好,但 kUTTypePNG 在 iOS 中未定义。常量的实际值是 "public.png",显然,用该值替换常量允许 iOS 可以很好地编译代码。

但是避免魔术 strings/numbers 是我们首先使用常量的原因 - 在 Swift-iOS 中是否有替代常量?

来自“iOS 技术概述”中的Mobile Core Services Framework

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.

所以

import MobileCoreServices

成就

public let kUTTypePNG: CFString

以及您的代码可用的其他 UTI 常量。