iOS
Swift
let version: String! = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let build: String! = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
Objective-C
NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
NSString *build = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
Android
Java
public static int getVersionCode(Context context){
PackageManager pm = context.getPackageManager();
int versionCode = 0;
try{
PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
versionCode = packageInfo.versionCode;
}catch(PackageManager.NameNotFoundException e){
e.printStackTrace();
}
return versionCode;
}
public static String getVersionName(Context context) {
PackageManager pm = context.getPackageManager();
String versionName = "";
try {
PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
versionName = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
もしくは
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;
Kotlin
fun getVersionCode(context: Context): Int {
val pm = context.packageManager
var versionCode = 0
try {
val packageInfo = pm.getPackageInfo(context.packageName, 0)
versionCode = packageInfo.versionCode
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return versionCode
}
fun getVersionName(context: Context): String {
val pm = context.packageManager
var versionName = ""
try {
val packageInfo = pm.getPackageInfo(context.packageName, 0)
versionName = packageInfo.versionName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return versionName
}
もしくは
val versionCode : Int = BuildConfig.VERSION_CODE
val versionName : String = BuildConfig.VERSION_NAME
2017/11/16追記
Androidにて、BuildConfigでの取得方法を追記しました。