如何在代码中获取当前版本的iOS项目? [英] How do I get the current version of my iOS project in code?

查看:130
本文介绍了如何在代码中获取当前版本的iOS项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to be able to get the current version of my iOS project/app as an NSString object without having to define a constant in a file somewhere. I don't want to change my version value in 2 places.

当我在项目目标摘要中碰撞我的版本时,需要更新该值。

The value needs to be updated when I bump my version in the Project target summary.

推荐答案

您可以按如下方式获取版本号和内部版本号:

You can get the version and build numbers as follows:

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

或在Objective-C中

or in Objective-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))"
    }
}

要点: https:/ /gist.github.com/ashleymills/6ec9fce6d7ec2a11af9b

这是Objective-C中的等价物:

Here's the equivalent in 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

这篇关于如何在代码中获取当前版本的iOS项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆