如何使用 Swift 获取应用程序的版本和内部版本号?
swiftserver side programmingprogramming更新于 2025/5/11 19:07:17
您经常需要处理 iOS 应用程序的版本和内部版本号。它可以帮助您在服务器端执行调试操作。您可以检查客户端(IOS 应用程序用户)具有哪个版本或内部版本。在此基础上,您可以调试来自客户端的问题。
可能需要向用户显示版本和内部版本号,以验证最终用户当前正在运行的版本和内部版本。
要获取 Swift 中的应用程序版本和内部版本号,您可以使用 Bundle 类,该类提供对应用程序的捆绑包信息的访问。
以下是如何使用 Swift 获取应用程序版本和内部版本号的示例 -
语法
请注意,object(forInfoDictionaryKey:) 方法返回一个可选项,因此您需要使用可选项绑定或强制解包来获取值。在上面的例子中,我使用了强制解包,这意味着如果应用程序的信息字典中不存在这些值,代码就会崩溃。您可能希望使用可选绑定来避免这种情况。
let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
基本上,我们从存储在应用程序主包中的 info.plist 文件中获取版本号。有一个预定义键 CFBundleVersion 可用于访问构建版本。
算法
步骤 1 − 访问主包对象
步骤 2 − 从主包对象访问信息字典对象
步骤 3 − 从 CFBundleShortVersionString 键访问构建版本
示例
假设您正在 Xcode 上的实际项目上运行以下代码 −
import Foundation
if let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
print("App version: \(appVersion)")
} else {
print("your platform does not support this feature.")
}
if let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String {
print("Build number: \(buildNumber)")
} else {
print("your platform does not support this feature.")
}
输出
your platform does not support this feature. your platform does not support this feature.
输出可能因您机器上当前运行的 Xcode 项目而异。
这会将应用程序版本和版本号打印到控制台。应用程序版本通常是"X.X.X"形式的字符串(例如"1.0.0"),而版本号则是表示应用程序版本号的字符串(例如"1")。
示例
假设您正在在线编译器上运行以下代码 -
import Foundation
if let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
print("App version: \(appVersion)")
} else {
print("your platform does not support this feature.")
}
if let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String {
print("Build number: \(buildNumber)")
} else {
print("your platform does not support this feature.")
}
输出
your platform does not support this feature. your platform does not support this feature.
结论
在 Swift 中,很多时候您需要使用构建和版本来执行某些操作。访问设备中使用的应用程序的当前版本是一个简单的过程。