Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the main app bundle from within extension

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.

like image 602
Jordan H Avatar asked Oct 04 '14 02:10

Jordan H


People also ask

What is bundle Main in iOS?

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.

What is app bundle Xcode?

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 ).


1 Answers

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.

like image 133
phatblat Avatar answered Oct 05 '22 01:10

phatblat