在 Swift 中获取包标识符

Anc*_*nek 1 cocoa foundation swift

我正在尝试使用应用程序的目录获取bundleID,但收到错误:EXC_BAD_ACCESS(code=1, address=0xd8)

应用程序.目录!是一个字符串

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)
Run Code Online (Sandbox Code Playgroud)

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

我在这里做错了什么?

Aks*_*Aks 5

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

Objective-C:

NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
Run Code Online (Sandbox Code Playgroud)

斯威夫特 3.0:

let bundleIdentifier =  Bundle.main.bundleIdentifier
Run Code Online (Sandbox Code Playgroud)

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

欲了解更多信息,请查看此处:

苹果文档: https://developer.apple.com/documentation/foundation/bundle#//apple_ref/occ/instm/NSBundle/bundleIdentifier