在 Swift 中获取包标识符

Getting bundle identifier in Swift

我正在尝试使用应用的目录获取 bundleID,但出现错误: EXC_BAD_ACCESS(代码=1,地址=0xd8)

application.directory!是一个字符串

let startCString = (application.directory! as NSString).UTF8String //Type: UnsafePointer<Int8>
let convertedCString = UnsafePointer<UInt8>(startCString) //CFURLCreateFromFileRepresentation needs <UInt8> pointer
let length = application.directory!.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
let dir = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, convertedCString, length, false)
let bundle = CFBundleCreate(kCFAllocatorDefault, dir)
let result = CFBundleGetIdentifier(bundle)

我在结果行中收到此错误。

我做错了什么?

您的代码的一个潜在问题是在

中获得的指针
let startCString = (application.directory! as NSString).UTF8String //Type: UnsafePointer<Int8>

仅在临时 NSString存在时有效。但是那个 编译器可以完成到 C 字符串的转换 "automatically" (比较 String value to UnsafePointer<UInt8> function parameter behavior),所以一个工作版本 应该是

let dir = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, path, Int(strlen(path)), false)
let bundle = CFBundleCreate(kCFAllocatorDefault, dir)
let result = CFBundleGetIdentifier(bundle)

但您可以简单地创建一个 NSBundle 从给定路径获取其标识符:

let ident = NSBundle(path: path)!.bundleIdentifier!

添加了错误检查的完整示例:

let path = "/Applications/TextEdit.app"

if let bundle = NSBundle(path: path) {
    if let ident = bundle.bundleIdentifier {
        print(ident) // com.apple.TextEdit
    } else {
        print("bundle has no identifier")
    }
} else {
    print("bundle not found")
}

如果您试图以编程方式获取它,您可以使用下面的代码行:

Objective-C:

NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];

Swift 3.0:

let bundleIdentifier =  Bundle.main.bundleIdentifier

(更新为最新的 swift 它适用于 iOS 和 Mac 应用程序。)

有关更多信息,请查看此处:

Apple Docs: https://developer.apple.com/documentation/foundation/bundle#//apple_ref/occ/instm/NSBundle/bundleIdentifier