Search code examples
xcodeswiftuiversionplisttarget

How to read Version & Build in Xcode from General/Targets in SwiftUI


in my first app (I wrote in SwiftUI) I want to add a Button to send me a mail for feedback, bugs, ... The button works perfect, but I want to add in this mail the current version and build of my app. Its showed in General/Targets/Identity. But i can't find a way to do this.

Button(action: {
    if let url = URL(string: "mailto:[email protected]?subject=MyApp%20Feedback&body=Hallo,%3Cbr%3Ei%20will%20tell%20you%20something%20about%20this%20app:%3Cbr%3E%3Cbr%3EVersion:%20\(AppVersionBuild)"){
        UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
    } 
}) {
    HStack{
        Image(systemName: "envelope")
        Text("send a mail to [email protected]")
    }
    .padding(10)
    .foregroundColor(.white)
    .background(LinearGradient(gradient: Gradient(colors: [Color("GradientStart"), Color("GradientEnd")]), startPoint: .topLeading, endPoint: .bottomTrailing))
    .cornerRadius(10, antialiased: false)
    .shadow(radius: 10)
}

Any idea how to get the version into the mail body (variable e.g. AppVersionBuild)?

Thank you


Solution

  • You can create a function that returns the version and build number

    func versionAndBuildNumber() -> String {
        let versionNumber = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
        let buildNumber = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
        if let versionNumber = versionNumber, let buildNumber = buildNumber {
            return "\(versionNumber) (\(buildNumber))"
        } else if let versionNumber = versionNumber {
            return versionNumber
        } else if let buildNumber = buildNumber {
            return buildNumber
        } else {
            return ""
        }
    }
    

    and replace \(AppVersionBuild) with the following \(versionAndBuildNumber())