ChatGPT解决这个技术问题 Extra ChatGPT

iOS:在代码中访问 app-info.plist 变量

我正在开发一个通用应用程序,并且想在我的代码中访问存储在 app-info.plist 文件中的值。

原因:我使用以下方法从情节提要动态地实例化 UIViewController:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
self = [storyboard instantiateViewControllerWithIdentifier:@"ExampleViewController"];

现在,上面的故事板名称@“MainStoryboard_iPhone”很丑。

我想做类似的事情:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:appInfo.mainStoryboardBaseNamePhone bundle:nil];
self = [storyboard instantiateViewControllerWithIdentifier:@"ExampleViewController"];

其中 appInfo 可能是 app-info.plist 中所有值的 NSDictionary


D
Damo

您项目的 info.plist 中的属性可通过以下方式直接访问...

[[NSBundle mainBundle] objectForInfoDictionaryKey:key_name];

例如,要获取版本号,您可以执行以下操作

NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];

有一个问题是版本号现在在 info.plist 中有两个属性 - 但你明白了吗?如果您将 info.plist 视为源代码(右键单击 info.plist - 选择 Open As),那么您将看到您可以使用的所有各种键名。


正如@Answerbot 在这篇文章中提到的:stackoverflow.com/a/4059118/1210822:“CFBundleVersion 已被重新用于构建,版本是 CFBundleShortVersionString”,所以现在要从 plist 中检索版本号,我们需要使用:NSString *version = [[NSBundle mainBundle ] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
对于 11.3,它不起作用,因为 NSBundle 已重命名,而新的 Bundle 尚未包含它。你有更新吗?
如果我有一个通过 Web 分发的企业 iOS 应用程序,我可以在 PLIST 文件中添加键/值对,然后在下载时从应用程序中读取这些值吗?
我们如何从 AppDelegate.m 更新 CFBundleVersion 的值?
M
Maverick

Damo's solutionSwift 4+ 语法

Bundle.main.object(forInfoDictionaryKey: "KEY_NAME")

例子

let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")

对于像我这样的初学者,Bundle 需要 import SystemConfiguration
r
rckoenes

那么你可以很容易地访问 info.plist :

获取故事板的名称:

NSString *storyboard  = [[NSBundle mainBundle].infoDictionary objectForKey:@"UIMainStoryboardFile"];

不确定它是否会检测到它是否在 iPad 中并且应该使用已设置的 UIMainStoryboardFile~ipad 键。


XCode 会根据设备自动使用 iPhone/iPad 故事板文件填充键 'UIMainStoryboardFile' :)
S
Stunner
NSString *path = [[NSBundle mainBundle] pathForResource: @"YOURPLISTNAME" ofType: @"plist"]; 
NSMutableDictionary *dictplist =[[NSMutableDictionary alloc] initWithContentsOfFile:path];

您还可以使用 NSDictionary:NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
s
svth

您还可以在 NSBundle 上使用 infoDictionary 方法:

NSDictionary *infoPlistDict = [[NSBundle mainBundle] infoDictionary];
NSString *version = infoPlistDict[@"CFBundleVersion"];