需要做升級(jí)判斷亲澡,or 要用到審核開(kāi)關(guān),就需要用到版本號(hào)的大小判斷纫版。
(之后找篇文章寫(xiě)寫(xiě)iOS審核開(kāi)關(guān)的事情<有點(diǎn)風(fēng)險(xiǎn)谷扣,不輕易亂學(xué)>
下面簡(jiǎn)單寫(xiě)了個(gè)版本字符串對(duì)比的小方法,
適用的格式是:1.2.2>1.2.1、1.2 > 1.1.9 会涎、1.2 = 1.2.0 裹匙。。末秃。也就是適用于xx.xx.xx.xx.....的純數(shù)字版本格式
以下是代碼:
+ (NSInteger)compareVersion:(NSString *)version1 toVersion:(NSString *)version2
{
NSArray *list1 = [version1 componentsSeparatedByString:@"."];
NSArray *list2 = [version2 componentsSeparatedByString:@"."];
for (int i = 0; i < list1.count || i < list2.count; i++)
{
NSInteger a = 0, b = 0;
if (i < list1.count) {
a = [list1[i] integerValue];
}
if (i < list2.count) {
b = [list2[i] integerValue];
}
if (a > b) {
return 1;//version1大于version2
} else if (a < b) {
return -1;//version1小于version2
}
}
return 0;//version1等于version2
}
接下來(lái)概页,說(shuō)說(shuō)我自己做版本升級(jí)判斷的方式:
主要是思路是:
- 將版本號(hào)存在本地NSUserDefaults里
- 和目前的CFBundleShortVersionString 進(jìn)行對(duì)比
/*
檢查首次安裝/升級(jí)
*/
+ (void)checkVersionFirstInstall:(void(^)())firstInstall
updateInstall:(void(^)())updateInstall
other:(void(^)())other
{
NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
NSUserDefaults *persistentDefaults = [NSUserDefaults standardUserDefaults];
NSString *localVersion = [persistentDefaults objectForKey:@"localVersion"];
if(!localVersion){
//首次安裝打開(kāi)
NSLog(@"首次安裝打開(kāi)");
if(firstInstall){
firstInstall();
}
//[self setLocalAppVersion]; 按需求看是否在這里就更新本地版本號(hào)
} else if([self compareVersion:appVersion toVersion:localVersion] == 1){
//升級(jí)打開(kāi)
NSLog(@"升級(jí)打開(kāi)");
if(updateInstall){
updateInstall();
}
//[self setLocalAppVersion];
} else {
//普通打開(kāi)
NSLog(@"普通打開(kāi)");
if(other){
other();
}
}
}
//將版本號(hào)存到本地
+ (void)setLocalAppVersion
{
NSString *localVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
NSUserDefaults *persistentDefaults = [NSUserDefaults standardUserDefaults];
[persistentDefaults setObject: localVersion forKey:@"localVersion"];
[persistentDefaults synchronize];
}