使用 Swift 获取版本和构建信息

问题描述 投票:0回答:16

我正在尝试访问主要

NSBundle
来检索 versionbuild 信息。问题是,我想在 Swift 中尝试一下,我知道如何在 Objective-C 中检索它:

text = [NSBundle.mainBundle.infoDictionary objectForKey:@"CFBundleVersion"];

但是我不知道从哪里开始使用 Swift,我尝试用新语法编写它但没有成功。

ios swift objective-c nsbundle
16个回答
185
投票

Swift 语法出了什么问题?这似乎有效:

if let text = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
    print(text)
}

134
投票

Swift 3/4 版本

func version() -> String {
    let dictionary = Bundle.main.infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as! String
    let build = dictionary["CFBundleVersion"] as! String
    return "\(version) build \(build)"
} 

Swift 2.x 版本

func version() -> String {
    let dictionary = NSBundle.mainBundle().infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as String
    let build = dictionary["CFBundleVersion"] as String
    return "\(version) build \(build)"
}

此处所见。


27
投票

ab 斯威夫特 5.0

我创建了一个包装器,以在我所有应用程序的一个位置获取一些 app 相关字符串,称为 AppInfo

/// Wrapper to get some app related strings at one place.
struct AppInfo {

   /// Returns the official app name, defined in your project data.
   var appName : String {
       return readFromInfoPlist(withKey: "CFBundleName") ?? "(unknown app name)"
   }

   /// Return the official app display name, eventually defined in your 'infoplist'.
   var displayName : String {
       return readFromInfoPlist(withKey: "CFBundleDisplayName") ?? "(unknown app display name)"
   }

   /// Returns the official version, defined in your project data.
   var version : String {
       return readFromInfoPlist(withKey: "CFBundleShortVersionString") ?? "(unknown app version)"
   }

   /// Returns the official 'build', defined in your project data.
   var build : String {
       return readFromInfoPlist(withKey: "CFBundleVersion") ?? "(unknown build number)"
   }

   /// Returns the minimum OS version defined in your project data.
   var minimumOSVersion : String {
    return readFromInfoPlist(withKey: "MinimumOSVersion") ?? "(unknown minimum OSVersion)"
   }

   /// Returns the copyright notice eventually defined in your project data.
   var copyrightNotice : String {
       return readFromInfoPlist(withKey: "NSHumanReadableCopyright") ?? "(unknown copyright notice)"
   }

   /// Returns the official bundle identifier defined in your project data.
   var bundleIdentifier : String {
       return readFromInfoPlist(withKey: "CFBundleIdentifier") ?? "(unknown bundle identifier)"
   }

   var developer : String { return "my awesome name" }

   // MARK: - Private stuff

   // lets hold a reference to the Info.plist of the app as Dictionary
   private let infoPlistDictionary = Bundle.main.infoDictionary

   /// Retrieves and returns associated values (of Type String) from info.Plist of the app.
   private func readFromInfoPlist(withKey key: String) -> String? {
    return infoPlistDictionary?[key] as? String
   }
}

坚果:

print("Name of the app: \(AppInfo().appName)")

18
投票

对于 Xcode 6 最终版本使用

NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String

“?” infoDictionary 之后的字符在这里很重要


16
投票

这是获取构建和版本的简单方法。

适用于 Swift 4.X

 if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
     print(version)
   }

 if let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
     print(build)
   }

对于目标C

NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];

NSString * currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

如果有任何问题请告诉我。这对我有用。


14
投票

快捷方式

AppName
AppVersion
BuildNumber
...

if let dict = NSBundle.mainBundle().infoDictionary {
   if let version = dict["CFBundleShortVersionString"] as? String,
       let bundleVersion = dict["CFBundleVersion"] as? String,
       let appName = dict["CFBundleName"] as? String {
           return "You're using \(appName) v\(version) (Build \(bundleVersion))."
   }
}

8
投票

很快,我会将其作为 UIApplication 的扩展,如下所示:

extension UIApplication {

    func applicationVersion() -> String {

        return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
    }

    func applicationBuild() -> String {

        return NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) as! String
    }

    func versionBuild() -> String {

        let version = self.applicationVersion()
        let build = self.applicationBuild()

        return "v\(version)(\(build))"
    }
}

然后您可以使用以下内容来获取您需要的一切:

let version = UIApplication.sharedApplication.applicationVersion() // 1
let build = UIApplication.sharedApplication.applicationBuild() // 80
let both = UIApplication.sharedApplication.versionBuild() // 1(80)

7
投票

//返回应用程序的版本号

public static var appVersion: String? {
    return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}

//返回应用程序的版本号

public static var appBuild: String? {
    return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String
}

2
投票

另一种选择是在 AppDelegate 中定义变量:

var applicationVersion:String {
    return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
}
var applicationBuild:String  {
    return NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) as! String
}
var versionBuild:String  {
    let version = self.applicationVersion
    let build = self.applicationBuild
    return "version:\(version) build:(\(build))"
}

可以在 AppDelegate 中作为变量引用


2
投票

此代码适用于 Swift 3、Xcode 8:

let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "0"
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? "0"

2
投票

对于 Swift 3,将 NSBundle 替换为 Bundle,mainBundle 则简单地替换为 main。

let AppVersion = Bundle.main.infoDictionary!["CFBundleVersion"] as! String

1
投票

[更新:Xcode 6.3.1] 我尝试了以上所有方法,但这些方法在 Xcode 6.3.1 中都不起作用,但我发现可以:

(NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String)!

0
投票

斯威夫特 3 :

let textVersion
 = Bundle.main.infoDictionary?["CFBundleVersion"] as? String

0
投票

SWIFT 3 版本

if let infoPath = Bundle.main.path(forResource: "Info.plist", ofType: nil),
        let infoAttr = try? FileManager.default.attributesOfItem(atPath: infoPath),
        let infoDate = infoAttr[.creationDate] as? Date
{
    return infoDate
}
return Date()

0
投票

从框架的捆绑包中获取版本

要获得框架结果,您可以使用

[访问框架捆绑包]

//inside framework
let version = bundle.infoDictionary?["CFBundleShortVersionString"] as? String

0
投票

Swift 100% 工作测试

您可以通过使用单个变量轻松获得这一点并将其公开。您可以在任何您想要的地方使用它。

(我正在获取 API 标头的用户代理)

public let userAgent: String = {
    if let info = Bundle.main.infoDictionary {
        let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
        let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
        let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
        let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"

        let osNameVersion: String = {
            let version = ProcessInfo.processInfo.operatingSystemVersion
            let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"

            let osName: String = {
                #if os(iOS)
                    return "iOS"
                #elseif os(watchOS)
                    return "watchOS"
                #elseif os(tvOS)
                    return "tvOS"
                #elseif os(macOS)
                    return "OS X"
                #elseif os(Linux)
                    return "Linux"
                #else
                    return "Unknown"
                #endif
            }()

            return "\(osName) \(versionString)"
        }()


        return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) "
    }

    return "MyApp"
}()

输出:

"User-Agent": "MyApp/4.6.0 (com.app.myapp; build:4.6.0.0; iOS 15.2.0) "
© www.soinside.com 2019 - 2024. All rights reserved.