2014-10-04 54 views
9

中獲取主要的應用程序包是否有可能從一個應用程序擴展名中包含應用程序的NSBundle得到什麼?我想獲取主應用的顯示名稱,而不是擴展名的顯示名稱。從擴展

回答

18

+mainBundle方法返回包含「當前應用程序可執行」,這是您的應用的子文件夾從分機內調用時的束。

該解決方案涉及剝離從束的URL 2個目錄層次,當在「APPEX」結束。

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

夫特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") 

夫特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擴展的xtension或目錄結構不斷變化。

+0

感謝這個!你是否能夠通過這種方式獲得AppStore應用程序? – ewindsor 2016-04-19 21:43:40

+0

是的,這裏沒有使用私有API。我們用這個在我們watchOS 1擴展到從主iOS應用包中加載的管理對象模型的'UIManagedDocument'。 – phatblat 2016-04-21 16:54:23

+0

啊真棒。感謝您的洞察力。 – ewindsor 2016-04-22 21:05:59