獲取 App 當前版本號
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
獲取 App Store 版本號
使用 get
請求 http://itunes.apple.com/lookup?id=你的AppStoreid
解析出來 JSON
是這樣的結構
resultDictionary = {"resultCount":1, "results": [{"version":"0.9.16", "...": "..."}]};
NSString *appStoreVersion = resultDictionary[@"results"][0][@"version"]
接下來就可以對這兩個版本號進行比較
比較當前版本號與App Store版本號
typedef NS_ENUM(NSUInteger, VersionCompare) {
VersionCompareNeedUpdate,
VersionCompareUnNeedUpdate
};
- (VersionCompare)compareStoreVersion:(NSString *)versionAppStore localVersion:(NSString *)versionLocal {
NSArray *arrayAppStore = [versionAppStore componentsSeparatedByString:@"."];
NSArray *arrayLocal = [versionLocal componentsSeparatedByString:@"."];
NSInteger shortCount = arrayAppStore.count<arrayLocal.count?arrayAppStore.count:arrayLocal.count;
for (NSInteger i = 0; i < shortCount; i++) {
if ([arrayAppStore[i] integerValue] > [arrayLocal[i] integerValue]) {
// App Store版本高,需要升級
return VersionCompareNeedUpdate;
} else if ([arrayAppStore[i] integerValue] < [arrayLocal[i] integerValue]) {
// App Store版本低,不需要升級
return VersionCompareUnNeedUpdate;
}
}
// 在相同位數下沒有得到結果,那么位數多的版本高
if (arrayAppStore.count > arrayLocal.count) {
return VersionCompareNeedUpdate;
} else {
return VersionCompareUnNeedUpdate;
}
}
調用
VersionCompare result = [self compareStoreVersion: appStoreVersion localVersion: appVersion];
switch (result) {
case VersionCompareNeedUpdate:
NSLog(@"需要升級");
break;
case VersionCompareUnNeedUpdate:
NSLog(@"不用升級");
break;
}