¿Cómo obtengo la versión de la aplicación y el número de compilación con Swift?


Tengo una aplicación IOS con un back-end de Azure y me gustaría registrar ciertos eventos, como inicios de sesión y qué versiones de los usuarios de la aplicación están ejecutando.

¿Cómo puedo devolver la versión y el número de compilación usando Swift?

 252
Author: Øyvind Vik, 2014-09-22

20 answers

EDITAR

Actualizado para Swift 4.2

let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String

EDITAR

Como señaló @azdev en la nueva versión de Xcode, obtendrá un error de compilación por probar mi solución anterior, para resolver esto solo edítelo como se sugiere para desenvolver el diccionario del paquete utilizando una !

let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]

End Edit

Simplemente use la misma lógica que en Objective-C pero con algunos pequeños cambios

//First get the nsObject by defining as an optional anyObject
let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary["CFBundleShortVersionString"]

//Then just cast the object as a String, but be careful, you may want to double check for nil
let version = nsObject as String

Espero que esto te ayude.

David

 214
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-28 13:20:24

Sé que esto ya ha sido respondido, pero personalmente creo que esto es un poco más limpio:

Swift 3.0:

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

Swift

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

De esta manera, la versión if let se encarga del procesamiento condicional (estableciendo el texto de la etiqueta en mi caso) y si infoDictionary o CFBundleShortVersionString son nil, el desempaquetado opcional hará que el código se omita.

 254
Author: Timothy Tripp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-14 21:09:33

Actualizado para Swift 3.0

Los NS-prefijos han desaparecido en Swift 3.0 y varias propiedades/métodos han cambiado de nombre para ser más rápidos. Así es como se ve ahora:

extension Bundle {
    var releaseVersionNumber: String? {
        return infoDictionary?["CFBundleShortVersionString"] as? String
    }
    var buildVersionNumber: String? {
        return infoDictionary?["CFBundleVersion"] as? String
    }
}

Bundle.main.releaseVersionNumber
Bundle.main.buildVersionNumber

Antigua Respuesta actualizada

He estado trabajando mucho con Frameworks desde mi respuesta original, así que quería actualizar mi solución a algo que es a la vez más simple y mucho más útil en un entorno multi-bundle:

extension NSBundle {

    var releaseVersionNumber: String? {
        return self.infoDictionary?["CFBundleShortVersionString"] as? String
    }

    var buildVersionNumber: String? {
        return self.infoDictionary?["CFBundleVersion"] as? String
    }

}

Ahora esto extensión será útil en aplicaciones para identificar tanto la principal paquete y cualquier otro paquete incluido (como un marco compartido para programación de extensiones o terceros frameworks como AFNetworking), así:

NSBundle.mainBundle().releaseVersionNumber
NSBundle.mainBundle().buildVersionNumber

// or...

NSBundle(URL: someURL)?.releaseVersionNumber
NSBundle(URL: someURL)?.buildVersionNumber

Respuesta original

Quería mejorar algunas de las respuestas ya publicadas. Escribí una extensión de clase que se puede agregar a su cadena de herramientas para manejar esto en una moda más lógica.

extension NSBundle {

class var applicationVersionNumber: String {
    if let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"]

Como? Cadena { versión de retorno } Número de Versión "return" No Disponible" }

class var applicationBuildNumber: String {
    if let build = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String {
        return build
    }
    return "Build Number Not Available"
}

}

Así que ahora puedes acceder a esto fácilmente por:

let versionNumber = NSBundle.applicationVersionNumber
 196
Author: Blake Merryman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-11 00:21:55

También sé que esto ya ha sido respondido, pero terminé las respuestas anteriores:

( * ) Actualizado para extensiones

extension Bundle {
    var releaseVersionNumber: String? {
        return infoDictionary?["CFBundleShortVersionString"] as? String
    }
    var buildVersionNumber: String? {
        return infoDictionary?["CFBundleVersion"] as? String
    }
    var releaseVersionNumberPretty: String {
        return "v\(releaseVersionNumber ?? "1.0.0")"
    }
}

Uso:

someLabel.text = Bundle.main.releaseVersionNumberPretty

@Obsoleto: Respuestas antiguas

Swift 3.1:

class func getVersion() -> String {
    guard let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else {
        return "no version info"
    }
    return version
}

Para versiones anteriores:

class func getVersion() -> String {
    if let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String {
        return version
    }
    return "no version info"
}

Así que si desea establecer el texto de la etiqueta o desea usar en otro lugar;

self.labelVersion.text = getVersion()
 53
Author: Gunhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-12 08:28:23

Hice una extensión en Bundle

extension Bundle {

    var appName: String {
        return infoDictionary?["CFBundleName"] as! String
    }

    var bundleId: String {
        return bundleIdentifier!
    }

    var versionNumber: String {
        return infoDictionary?["CFBundleShortVersionString"] as! String 
    }

    var buildNumber: String {
        return infoDictionary?["CFBundleVersion"] as! String
    }

}

Y luego usarlo

versionLabel.text = "\(Bundle.main.appName) v \(Bundle.main.versionNumber) (Build \(Bundle.main.buildNumber))"
 25
Author: carmen_munich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-18 15:37:47

Para Swift 4.0

let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"]!
let build = Bundle.main.infoDictionary!["CFBundleVersion"]!
 22
Author: Iryna Batvina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-04 20:13:39

Para Swift 3.0 NSBundle no funciona, Seguir el código funciona perfectamente.

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

Y solo para el número de compilación, es:

let buildNumberString =
      Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")
          as! String

Confusamente 'CFBundleVersion' es el número build como se introdujo en Xcode en General->Identity.

 16
Author: Tejas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-19 06:42:40

Xcode 8, Swift 3:

let gAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "0"
let gAppBuild = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? "0"
 12
Author: Crashalot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-26 06:46:17

Mi respuesta (como en agosto de 2015), dado que Swift sigue evolucionando:

let version = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String
 9
Author: Charlie Seligman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-22 14:31:07

Xcode 9.4.1 Swift 4.1

Tenga en cuenta el uso de localizedInfoDictionary para elegir la versión de idioma correcta del nombre para mostrar del paquete.

var displayName: String?
var version: String?
var build: String?

override func viewDidLoad() {
    super.viewDidLoad()

    // Get display name, version and build

    if let displayName = Bundle.main.localizedInfoDictionary?["CFBundleDisplayName"] as? String {
        self.displayName = displayName
    }
    if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
        self.version = version
    }
    if let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
        self.build = build
    }
}
 8
Author: Hugo F,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-12 16:07:30

Habiendo mirado la documentación, creo que lo siguiente es más limpio:

let version = 
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") 
as? String

Fuente: "El uso de este método es preferible a otros métodos de acceso porque devuelve el valor localizado de una clave cuando está disponible."

 6
Author: Daniel Armyr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-26 07:20:50

Para Swift 1.2 es:

let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
let build = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String
 5
Author: Michael Samoylov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-20 20:45:25

Swift 3:

Número De Versión

if let versionNumberString = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { // do something }

Número de construcción

if let buildNumberString = Bundle.main.infoDictionary?["CFBundleVersion"] as? String { // do something }
 4
Author: jasonnoahchoi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-29 17:05:21

Swift 4

func getAppVersion() -> String {
    return "\(Bundle.main.infoDictionary!["CFBundleShortVersionString"] ?? "")"
}

Paquete.principal.infoDictionary!["CFBundleShortVersionString"]

Sintaxis antigua de Swift

let appVer: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
 3
Author: Harshil Kotecha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-04 12:05:35
extension UIApplication {

    static var appVersion: String {
        if let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") {
            return "\(appVersion)"
        } else {
            return ""
        }
    }

    static var build: String {
        if let buildVersion = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) {
            return "\(buildVersion)"
        } else {
            return ""
        }
    }

    static var versionBuild: String {
        let version = UIApplication.appVersion
        let build = UIApplication.build

        var versionAndBuild = "v\(version)"

        if version != build {
            versionAndBuild = "v\(version)(\(build))"
        }

        return versionAndBuild
    }

}

Atención: Usted debe utilizar si dejar aquí en caso de que la versión de la aplicación o construir no se establece lo que dará lugar a accidente si intenta utilizar ! desenvolver.

 2
Author: futantan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-27 04:03:15
public var appVersionNumberString: String {
get {
    return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
}
}
 2
Author: RaziPour1993,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-23 11:27:54

Aquí está una versión actualizada de Swift 3.2:

extension UIApplication
{
    static var appVersion:String
    {
        if let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")
        {
            return "\(appVersion)"
        }
        return ""
    }

    static var buildNumber:String
    {
        if let buildNum = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String)
        {
            return "\(buildNum)"
        }
        return ""
    }

    static var versionString:String
    {
        return "\(appVersion).\(buildNumber)"
    }
}
 1
Author: BadmintonCat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-14 05:47:33

SWIFT 4

/ / Primero obtenga el NSObject definiendo como un AnyObject opcional

let nsObject: AnyObject? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as AnyObject

/ / A continuación, simplemente cast el objeto como una cadena, pero tenga cuidado, es posible que desee comprobar dos veces para nil

let version = nsObject as! String
 1
Author: Prabhat Kasera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-10 17:13:08

Para cualquier persona interesada, hay una biblioteca bonita y ordenada llamada SwifterSwift disponible en github y también completamente documentada para cada versión de swift (ver swifterswift.com).

Usando esta biblioteca, leer la versión de la aplicación y el número de compilación sería tan fácil como esto:

import SwifterSwift

let buildNumber = SwifterSwift.appBuild
let version = SwifterSwift.appVersion
 0
Author: MFA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-08 12:22:45

Para Swift 2.0

//First get the nsObject by defining as an optional anyObject

let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
let version = nsObject as! String
 -1
Author: Aadi007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-04 14:06:55