从 Info.plist 文件中读取版本号。

94

我想从 Info.plist 中读取捆绑版本信息并将其作为字符串传递到我的代码中。我应该如何做到这一点?

5个回答

205

您可以将Info.plist作为字典读取:

[[NSBundle mainBundle] infoDictionary]

你可以轻松地通过CFBundleVersion键获取版本。

最后,你可以使用下列方式获取版本:

NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
NSString* version = [infoDict objectForKey:@"CFBundleVersion"];

完美。这比我使用的所有CF*函数的代码行数要简单得多...我确定必须有一种快速获取NSDictionary的方法。 - Stew
16
对于版本号,这并不重要,但对于其他键,您可能希望使用 objectForInfoDictionaryKey: 来获取本地化值(如果有的话):[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"] - Zargony
20
在Xcode4中,如果您查看目标的摘要面板,您将看到版本和构建字段。CFBundleVersion已被重新用作构建版本号,而版本号则是CFBundleShortVersionString - memmons
5
这段代码可以获取应用程序的版本号和构建号,并将它们格式化在一起: NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; NSString *build = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]; self.versionLabel.text = [NSString stringWithFormat:@"%@.%@", version, build]; - Graham Perks
使用CFBundleShortVersionString作为key来调用objectForKey方法。 - ayalcinkaya
我认为对于版本号,使用objectForInfoDictionaryKey:是可取的,因为所谓的“产品版本”(CFBundleShortVersionString)可能包含文本并且可以本地化。 - Motti Shneor

13

对于Swift用户:

if let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") {
    print("version is : \(version)")
}

针对Swift3用户:

if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") {
    print("version is : \(version)")
}

5

我知道一些时间已经过去了,自从这个问题提出和回答之后。

iOS8以后,原先被接受的答案可能已经不再适用。

现在有一个新的方法来解决它:

NSString *version = (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey);

6
你有为什么会这样的链接吗? - Ian Warburton

4

在iOS 8中,这两个字段都是必需的。之前,没有CFBundleShortVersionString也可以运行。但现在,这是在App Store提交任何应用程序所需的plist字段。并且kCFBundleVersionKey会与每个新版本上传进行比较,必须按增量顺序排列。特别是对于TestFlight构建。我是这样做的,

NSString * version = nil;
    version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    if (!version) {
        version = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
    }

谢谢。version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; 对我有用。 - swiftBoy

3

Swift 3:

let appBuildNumber = Bundle.main.infoDictionary!["CFBundleVersion"] as! String
let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接