我想确保反序列化配置文件中的 plist,而不是搜索字符串。
import UIKit
public extension UIDevice {
enum PushEnvironment: String {
case unknown
case development
case production
}
var pushEnvironment: PushEnvironment {
guard let provisioningProfile = try? provisioningProfile(),
let entitlements = provisioningProfile["Entitlements"] as? [String: Any],
let environment = entitlements["aps-environment"] as? String
else {
return .unknown
}
return PushEnvironment(rawValue: environment) ?? .unknown
}
// MARK: - Private
private func provisioningProfile() throws -> [String: Any]? {
guard let url = Bundle.main.url(forResource: "embedded", withExtension: "mobileprovision") else {
return nil
}
let binaryString = try String(contentsOf: url, encoding: .isoLatin1)
let scanner = Scanner(string: binaryString)
guard scanner.scanUpToString("<plist") != nil, let plistString = scanner.scanUpToString("</plist>"),
let data = (plistString + "</plist>").data(using: .isoLatin1)
else {
return nil
}
return try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any]
}
}
您可以使用它来执行以下操作:
UIDevice.current.pushEnvironment == .production
当我告诉我的 API 关于我的设备时,我包括UIDevice.current.pushEnvironment.rawValue
并且 API 可以使用适当的证书和网关来发送设备通知。