我想从 Info.plist 中读取捆绑版本信息并将其作为字符串传递到我的代码中。我应该如何做到这一点?
我想从 Info.plist 中读取捆绑版本信息并将其作为字符串传递到我的代码中。我应该如何做到这一点?
您可以将Info.plist作为字典读取:
[[NSBundle mainBundle] infoDictionary]
你可以轻松地通过CFBundleVersion
键获取版本。
最后,你可以使用下列方式获取版本:
NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
NSString* version = [infoDict objectForKey:@"CFBundleVersion"];
对于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)")
}
我知道一些时间已经过去了,自从这个问题提出和回答之后。
iOS8以后,原先被接受的答案可能已经不再适用。
现在有一个新的方法来解决它:
NSString *version = (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey);
在iOS 8中,这两个字段都是必需的。之前,没有CFBundleShortVersionString
也可以运行。但现在,这是在App Store提交任何应用程序所需的plist字段。并且kCFBundleVersionKey
会与每个新版本上传进行比较,必须按增量顺序排列。特别是对于TestFlight构建。我是这样做的,
NSString * version = nil;
version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if (!version) {
version = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
}
Swift 3:
let appBuildNumber = Bundle.main.infoDictionary!["CFBundleVersion"] as! String
let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
objectForInfoDictionaryKey:
来获取本地化值(如果有的话):[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]
。 - ZargonyCFBundleVersion
已被重新用作构建版本号,而版本号则是CFBundleShortVersionString
。 - memmonsNSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; NSString *build = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]; self.versionLabel.text = [NSString stringWithFormat:@"%@.%@", version, build];
- Graham PerksobjectForInfoDictionaryKey:
是可取的,因为所谓的“产品版本”(CFBundleShortVersionString
)可能包含文本并且可以本地化。 - Motti Shneor