iOS本地版本和商店版本號的獲取與比較

獲取 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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容