Swift: Get App Version - Easy Steps
When developing an app using Swift, it's important to manage and display the version number correctly. Users often look for this information to check for updates or identify the version they're using. Here's a comprehensive guide on how to get your app's version number in Swift.
Before we dive into the code, let's understand a bit about app versioning. In iOS, the app version is represented by a tuple of four integers, commonly known as the CFBundleVersion and CFBundleShortVersionString keys in the app's Info.plist file.
Accessing App Version Number
The first step in displaying the app's version number is to access it. Swift allows us to retrieval these values using the `Bundle.main` property and the `object(forInfoDictionaryKey:)` method.
Remember to define your app's version number in your 'Info.plist' file. This ensures that your code can access the information.
Getting the Short Version String
To get the app's short version string (the visible version number users see in the App Store), use the following code:
let shortVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "Unknown"
print("Short Version: \(shortVersion)")
Getting the Full Version Number
To retrieve the full version number (used under the hood for updating and testing), use the following code:
let fullVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "Unknown"
print("Full Version: \(fullVersion)")
Displaying the App Version Number
Once you have accessed the app's version number, you can display it anywhere in your app. Here's how you can display it in your app's Settings view:
Displaying in Settings
First, add a new Settings item in your 'Info.plist' file:
Then, add a new extension to your 'UIApplication':
extension UIApplication {
var appVersionNumber: String? {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
}
And access it like this:
let appVersion = UIApplication.shared.appVersionNumber
if let version = appVersion {
print("App Version: \(version)")
}
Displaying in a Label
You can also display the app's version number in a UILabel as follows:
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "Unknown"
appVersionLabel.text = "App Version: \(appVersion)"
By following these steps, you can easily manage and display your app's version number in Swift. Staying on top of versioning can help you provide a better user experience and make app updates easier.