Joey Joey - 5 months ago 33
Swift Question

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.

Answer

The +mainBundle method returns the bundle containing the "current application executable", which is a subfolder of your app when called from within an extension.

The solution that I've found involved peeling off two directory levels from the URL of the bundle, when it ends in "appex".

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"];

This will break if the pathExtension or the directory structure for an iOS extension ever changes.

Comments