swift - 在 Swift 中获取包标识符

标签 swift cocoa foundation

我正在尝试使用应用程序的目录获取 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)

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

我在这里做错了什么?

最佳答案

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

目标-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

关于swift - 在 Swift 中获取包标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673780/

相关文章:

Swift 4 Objective-C 运行时和转换为 NSObjectProtocol

Linux 上的 Swift 2.2, "use of unresolved identifier ' 退出'”

ios - 无法从 HealthKit 获取合理格式的 HRV 读数

ios - 一个 ViewController 中存在多个 UIPickerView

objective-c - 为什么我的 CATextLayer 不响应contentsGravity 属性?

ios - 使用 distantFuture 的实际例子是什么?

ios - 无法在 Swift 中调整多个设备上的布局

swift - Firestore - 加载 View 时 append 到 tableView

objective-c - 如何从另一个类访问变量?

iphone - NSURLConnection 和处理响应代码和响应数据