How do I get the App version and build number using Swift?

前端 未结 30 1046
暖寄归人
暖寄归人 2020-12-22 15:21

I have an IOS app with an Azure back-end, and would like to log certain events, like logins and which versions of the app users are running.

How can I return the ver

30条回答
  •  感动是毒
    2020-12-22 15:44

    I know this has already been answered but personally I think this is a little cleaner:

    Swift 3.0:

     if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
        self.labelVersion.text = version
    }
    

    Swift <2.3

    if let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String {
        self.labelVersion.text = version
    }
    

    This way, the if let version takes care of the conditional processing (setting the label text in my case) and if infoDictionary or CFBundleShortVersionString are nil the optional unwrapping will cause the code to be skipped.

提交回复
热议问题