从扩展中获取主应用程序包
是否有可能从应用程序扩展中获取包含应用程序的NSBundle
? 我想获得主应用程序的显示名称,而不是扩展名的显示名称。
+mainBundle
方法返回包含“当前应用程序可执行文件”的包,该文件是在扩展中调用时的应用程序的子文件夹。
这个解决scheme涉及从bundle的URL剥离两个目录级别,当它以“appex”结束时。
Objective-C的
NSBundle *bundle = [NSBundle mainBundle]; if ([[bundle.bundleURL pathExtension] isEqualToString:@"appex"]) { // Peel off two directory levels - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex bundle = [NSBundle bundleWithURL:[[bundle.bundleURL URLByDeletingLastPathComponent] URLByDeletingLastPathComponent]]; } NSString *appDisplayName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
Swift 2.2
var bundle = NSBundle.mainBundle() if bundle.bundleURL.pathExtension == "appex" { // Peel off two directory levels - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex bundle = NSBundle(URL: bundle.bundleURL.URLByDeletingLastPathComponent!.URLByDeletingLastPathComponent!)! } let appDisplayName = bundle.objectForInfoDictionaryKey("CFBundleDisplayName")
Swift 3
var bundle = Bundle.main if bundle.bundleURL.pathExtension == "appex" { // Peel off two directory levels - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex let url = bundle.bundleURL.deletingLastPathComponent().deletingLastPathComponent() if let otherBundle = Bundle(url: url) { bundle = otherBundle } } let appDisplayName = bundle.object(forInfoDictionaryKey: "CFBundleDisplayName")
如果iOS扩展的pathExtension或目录结构发生更改,这将会中断。