有些App更新新功能并且上线后,会有这样的需求:用户登录后,会提示用户“发现新版本,请更新”,这就需要用户点击确定后,跳转AppStore下载。以下是我的实现方法:
原理:
每个上架的苹果应用程序,都会有一个应用程序的ID。根据这个ID我们就可以获取到当前程序的最新版本号,然后和自己的版本号作比较,如果一样的话就是最新版,反之就不是新版。然后就可以提示用户来手动下载最新版的程序。
1、获当前版本号
NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
NSString *currentVersion = infoDic[@"CFBundleShortVersionString"];
NSLog(@"【1】当前为自动检测检测,当前版本号为:%@",currentVersion);
2、链接Itunes获取应用商店版本号
NSError*error;
NSData*response = [NSURLConnectionsendSynchronousRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:[NSStringstringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",你的AppID]]]returningResponse:nilerror:nil];
NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(@"可输出一下看看%@",appInfoDic);
NSArray *array = appInfoDic[@"results"];
if(array.count < 1) {
NSLog(@"此APPID为未上架的APP或者查询不到");
return;
}
NSDictionary*dic = array[0];
//AppStore版本号
NSString*appStoreVersion = dic[@"version"];
NSLog(@"当前版本号:%@---商店版本号:%@",currentVersion,appStoreVersion);
3、比较版本号,当前版本号 < AppStore版本号 提示更新
currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"."withString:@""];
if(currentVersion.length == 2) {
currentVersion = [currentVersion stringByAppendingString:@"0"];
}else if (currentVersion.length==1){
currentVersion = [currentVersion stringByAppendingString:@"00"];
}
appStoreVersion = [appStoreVersion stringByReplacingOccurrencesOfString:@"."withString:@""];
if(appStoreVersion.length == 2) {
appStoreVersion = [appStoreVersion stringByAppendingString:@"0"];
}elseif(appStoreVersion.length ==1){
appStoreVersion= [appStoreVersion stringByAppendingString:@"00"];
}
4、比较版本,然后更新
if([currentVersion floatValue] < [appStoreVersion floatValue]) {
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"版本有更新"message:[NSString stringWithFormat:@"检测到新版本(%@),是否更新?",dic[@"version"]]preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction*sureAction = [UIAlertActionactionWithTitle:@"更新"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction){
NSURL*url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/id%@?ls=1&mt=8",你的AppID]];
[[UIApplicationsharedApplication]openURL:url];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancelhandler:nil];
[alertCaddAction:sureAction];
[alertCaddAction:cancelAction];
[selfpresentViewController:alertCanimated:YEScompletion:nil];
}