我正在尝试使用app的目录获取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)
我在结果行上收到此错误。
我在这里做错了什么?
答案 0 :(得分:2)
代码的一个潜在问题是在
中获得指针let startCString = (application.directory! as NSString).UTF8String //Type: UnsafePointer<Int8>
仅当临时 NSString
存在时,才有效。但那 转换为C字符串可以由编译器“自动”完成 (比较Colorbox: DON't close #colorbox on click within #colorbox inside #cboxOverlay),这是一个有效的版本 应该是
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")
}
答案 1 :(得分:2)
如果您尝试以编程方式获取它,可以使用以下代码行:
目标-C:
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
Swift 3.0:
let bundleIdentifier = Bundle.main.bundleIdentifier
Updated for latest swift It will work for both iOS and Mac apps.
了解更多信息,请点击此处:
Apple Docs: https://developer.apple.com/documentation/foundation/bundle#//apple_ref/occ/instm/NSBundle/bundleIdentifier