How to get the current version of my iOS project in code?

iOSiPhone/iPadMobile Development

When we build an iOS application, by default it get a version 1.0 and build 0. Whenever we upload a new build to the app store, we need to change the version number. We can update the build number for testing builds. The version and build number are stored in the info.plist file in our project.

Sometimes we might need to access the build or the version number in our application to perform some custom action.

To get the version number we can use the following code and assign it to a variable or constant.

Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String

To get the build number we can use the below code

Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String

For an example, we can use the above code in our viewDidLoad to access these values and print.

override func viewDidLoad() {
   super.viewDidLoad()
   let currentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
   let currentBuild = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
   print(currentVersion,".",currentBuild)
}

When we run the above code we will get our version number followed by a “.” and the build number.

raja
Published on 21-Jan-2019 12:11:04
Advertisements