如何在代码中获得当前版本的IOS项目?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (23)

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

当我在Project目标摘要中插入我的版本时,需要更新该值。

提问于
用户回答回答于

可以获得版本和生成编号如下:

let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let appBundle = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String

或目标C

NSString * version = [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
NSString * build = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];

我在一个类别中有以下方法UIApplication:

extension UIApplication {

    class func appVersion() -> String {
        return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
    }

    class func appBuild() -> String {
        return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
    }

    class func versionBuild() -> String {
        let version = appVersion(), build = appBuild()

        return version == build ? "v\(version)" : "v\(version)(\(build))"
    }
}

以下是目标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;
}

用户回答回答于

下面是我们所做的工作Xcode 8,SWIFT 3:

let gAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "0"
let gAppBuild = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? "0"

print("Version: \(gAppVersion)")
print("Build: \(gAppBuild)")

扫码关注云+社区