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

后端 未结 8 1340
挽巷
挽巷 2020-12-12 10:23

I would like to be able to get the current version of my iOS project/app as an NSString object without having to define a constant in a file somewhere. I don\'t

8条回答
  •  不知归路
    2020-12-12 10:48

    [Swift version: 5.2]

    All iOS apps must store an app version number in their Info.plist file, but there’s no build-in way to get that as a string you can use in your code.

    I have created one small extension to UIApplication that reads the Info.plist file and returns a version number automatically.

    Here’s the code:

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

    Inside Your Controller

    @IBOutlet weak var tv_version: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
       
        //Display Version
        setUpCurrentVersion()
    }
    
    
    func setUpCurrentVersion(){
        tv_version.text = "v" + UIApplication.appVersion!
    }
    

提交回复
热议问题