从扩展程序中获取主应用程序包 [英] Get the main app bundle from within extension

查看:191
本文介绍了从扩展程序中获取主应用程序包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从应用扩展程序中获取包含应用的 NSBundle ?我想获取主应用程序的显示名称,而不是扩展程序的显示名称。

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.

推荐答案

+ mainBundle 方法返回包含当前应用程序可执行文件的包,它是从扩展程序中调用时应用程序的子文件夹。

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

这解决方案涉及从包的URL中剥离两个目录级别,当它以appex结束时。

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

如果iOS扩展的pathExtension或目录结构发生变化,这将会中断。

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

这篇关于从扩展程序中获取主应用程序包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆