我們在開發中經常需要判斷當前版本去做相應的操作,比如跳轉到AppStore進行更新或判斷該App是否第一次打開等。首先我們應該知道xcode中的顯示位置如下:
image.png
Image2.png
1、首先我們可以在General的Version或infoPlist字典中的Bundle versions string, short鍵看到,二者是一樣的,即我們在Version中更改版本之后后者也會自動更改。
我們可以通過代碼打印系統的infoPlist中的字典
NSString *infoDic = [NSBundle mainBundle].infoDictionary;
如下是該字典中的部分鍵值
{
BuildMachineOSBuild = 15G1004;
CFBundleDevelopmentRegion = en;
CFBundleExecutable = "\U90a3\U4f60\U8bf4\U5427";
CFBundleIdentifier = "com.example";
CFBundleInfoDictionaryVersion = "6.0";
CFBundleName = "\U90a3\U4f60\U8bf4\U5427";
CFBundleNumericVersion = 16809984;
CFBundlePackageType = APPL;
CFBundleShortVersionString = "1.0";//項目版本
}
所以我們通過字典中的CFBundleShortVersionString鍵得到當前版
NSString *currentVersion = [infoDic objectForKey:@"versionKey"];```
2、判斷當前版本是否是第一次打開
+ (void)judgeNewVersion
{
NSString *versionKey = @"CFBundleShortVersionString";
//infoPlist中的版本
NSString * version = [NSBundle mainBundle].infoDictionary[versionKey];
//取出上次存儲的版本號
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *str = [defaults objectForKey:@"CFBundleShortVersionString"];
//對比兩次版本后是否相同
UIWindow*window = [UIApplication sharedApplication].keyWindow;
if (![version isEqualToString:str]) { //如果當前版本第一次打開,做相應的操作(比如顯示新特性控制器控制器)
window.rootViewController = [[新特性控制器 alloc] init];
//將新版本儲存到沙盒中
[defaults setObject:version forKey:@"CFBundleShortVersionString"];
[defaults synchronize];
} else {//如果當前版本不是第一次打開直接顯示默認根控制器
[UIApplication sharedApplication].statusBarHidden = NO;
window.rootViewController = [[根控制器 alloc]init];
}
}
<br>
3、判斷當前版本和服務器版本是否一樣
+ (void)judgeNewVersion
{
NSString *versionKey = @"CFBundleShortVersionString";
//infoPlist中的版本
NSString *version = [NSBundle mainBundle].infoDictionary[versionKey];
//服務器請求數據獲得最新的版本
NSString *newVersion = getThelatestVersionFromServer;
//對比兩次版本后是否相同
UIWindow*window = [UIApplication sharedApplication].keyWindow;
if(![version isEqualToString:newVersion]){//當不是最新版本的時候提示用戶更新
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"更新版本有更好體驗,請下載最新版本" delegate:self cancelButtonTitle:@"立即更新" otherButtonTitles:@"暫不更新",nil];
[alert show];
}else{//如果已經是最新版本直接顯示默認根控制器
[UIApplication sharedApplication].statusBarHidden = NO;
window.rootViewController = [[HMTabBarController alloc]init];
}
}