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[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;
}

你可能感兴趣的:(iOS本地版本和商店版本号的获取与比较)