Answers:
您可以获取版本和内部版本号,如下所示:
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
或在Objective-C中
NSString * version = [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
NSString * build = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
我在以下类别中具有以下方法UIApplication
:
extension UIApplication {
static var appVersion: String {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
}
static var appBuild: String {
return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
}
static var versionBuild: String {
let version = appVersion, build = appBuild
return version == build ? "v\(version)" : "v\(version)(\(build))"
}
}
要点: https : //gist.github.com/ashleymills/6ec9fce6d7ec2a11af9b
这与Objective-C中的等效项:
+ (NSString *) appVersion
{
return [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
}
+ (NSString *) build
{
return [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
}
+ (NSString *) versionBuild
{
NSString * version = [self appVersion];
NSString * build = [self build];
NSString * versionBuild = [NSString stringWithFormat: @"v%@", version];
if (![version isEqualToString: build]) {
versionBuild = [NSString stringWithFormat: @"%@(%@)", versionBuild, build];
}
return versionBuild;
}
要点: https : //gist.github.com/ashleymills/c37efb46c9dbef73d5dd
(NSString *)kCFBundleVersionKey
而不是@"CFBundleVersion"
。即使输入的时间更长(自动完成功能会有所帮助),因为它是一个常量,因此会在编译时进行检查。
NSBundle
而不是UIApplication
将扩展替换为实例调用。
UIApplication
,因为返回的信息与应用程序有关。另外,这仅适用于main
包-在任何包上将其设为实例方法是没有意义的。
build
什么意思appBundle
(在代码的第二行)?
在目标C中:
1)要获取App版本,您必须使用:
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
2)要获得Build版本,您必须使用:
NSString *buildVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
在Swift中,您可以使用以下方法获取捆绑包版本:
let info:NSDictionary = NSBundle.mainBundle().infoDictionary!
let version:String = info.objectForKey("CFBundleShortVersionString") as! String
versionLabel.text = "Version:" + version
我的一个开源项目App Update Tracker以类方法的形式提供此功能(及更多功能):
+ (NSString *)getShortVersionString
+ (NSString *)getLongVersionString
您可以这样使用它:
#import "AppUpdateTracker.h"
NSLog(@"short version: %@", [AppUpdateTracker getShortVersionString]);
NSLog(@"long version: %@", [AppUpdateTracker getLongVersionString]);
因此,以下是这两种的Swift版本:
let versionNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String
它包含在此仓库中,请查看: