一尘不染

如何用代码获取当前版本的iOS项目?

swift

我希望能够将iOS项目/应用程序的当前版本作为NSString对象,而不必在文件中的某个位置定义常量。我不想在2个地方更改版本值。

当我在“项目”目标摘要中更改版本时,需要更新该值。


阅读 232

收藏
2020-07-07

共1个答案

一尘不染

您可以获取版本和内部版本号,如下所示:

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

2020-07-07