Is it possible to get the containing app's NSBundle
from within an app extension? I would like to get the main app's display name, not the extension's display name.
The Bundle class has many constructors, but the one you use most often is main . The main bundle represents the bundle directory that contains the currently executing code. So for an app, the main bundle object gives you access to the resources that shipped with your app.
A bundle can contain executable code, images, sounds, nib files, private frameworks and libraries, plug-ins, loadable bundles, or any other type of code or resource. It also contains a runtime-configuration file called the information property list ( Info. plist ).
The +mainBundle
method returns the bundle containing the "current application executable", which is a subfolder of your app when called from within an extension.
This solution involves peeling off two directory levels from the URL of the bundle, when it ends in "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")
This will break if the pathExtension or the directory structure for an iOS extension ever changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With