【问题标题】:Read version from Info.plist从 Info.plist 读取版本
【发布时间】:2010-10-30 14:25:12
【问题描述】:

我想将 Info.plist 中的包版本信息读入我的代码,最好是作为字符串。我该怎么做?

【问题讨论】:

    标签: iphone objective-c cocoa-touch xcode info.plist


    【解决方案1】:

    你可以把你的 Info.plist 当作字典来阅读

    [[NSBundle mainBundle] infoDictionary]
    

    您可以通过这种方式轻松地通过CFBundleVersion 键获取版本。

    最后,你可以得到版本

    NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString* version = [infoDict objectForKey:@"CFBundleVersion"];
    

    【讨论】:

    • 完美。这比我使用的所有 CF* 函数行要简单得多......我确信一定有一种快速的方法来获取 NSDictionary。
    • 对于版本号,这无关紧要,但对于其他键,您可能希望使用objectForInfoDictionaryKey:,因为如果可用,它会返回本地化值:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]
    • 请注意,在 Xcode4 中,如果您查看目标的摘要面板,您将看到版本和构建字段。 CFBundleVersion 已改用于 Build 版本,版本为 CFBundleShortVersionString
    • 这将获取版本和内部版本号,并将它们格式化在一起:NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];NSString *build = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];self.versionLabel.text = [NSString stringWithFormat:@"%@.%@", version, build];
    • 使用 CFBundleShortVersionString 作为 objectForKey 方法的键。
    【解决方案2】:

    对于 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)")
    }
    

    【讨论】:

      【解决方案3】:

      我知道距离任务和答案已经过去了一段时间。

      由于 iOS8,接受的答案可能不起作用。

      这是现在的新方法:

      NSString *version = (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey);
      

      【讨论】:

      • 你有链接说明为什么会这样吗?
      【解决方案4】:

      现在在 iOS 8 中,这两个字段都是必需的。之前它可以在没有CFBundleShortVersionString 的情况下工作。但现在在应用商店中提交任何应用都是必填的 plist 字段。并且kCFBundleVersionKey 用于上传每个新版本,必须按递增顺序进行。专门用于 TestFlight 构建。我是这样做的,

      NSString * version = nil;
          version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
          if (!version) {
              version = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
          }
      

      【讨论】:

      • 谢谢.. version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; 为我工作
      【解决方案5】:

      斯威夫特 3:

      let appBuildNumber = Bundle.main.infoDictionary!["CFBundleVersion"] as! String
      let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-10
        • 2012-05-11
        • 2015-05-21
        • 1970-01-01
        • 2016-05-11
        • 1970-01-01
        • 2012-09-05
        • 1970-01-01
        相关资源
        最近更新 更多