APP中提示用户更新版本是很有必要的,可以增加用户的粘合度,更好的体验产品。
版本升级提示启示很简单,大致分为三步:
第一步:获取手机上安装的APP的版本号和AppStore中最新的版本号
第二步:对获取的版本号进行比较
第三步:前往AppStore进行更新
下面就是具体的实现代码:
需要说明的是 从AppStore中获取版本号是POST请求, 最精准的方式是通过 AppID获取APP基本信息
#define APP_URL @"http://itunes.apple.com/lookup?id=你的AppID"
- (void)checkVersion
{
// 创建会话
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:APP_URL]];
request.HTTPMethod = @"POST";
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"网上获取版本号 %@", dic);
// 获取手机中当前的版本号
NSDictionary *dicphone = [[NSBundle mainBundle] infoDictionary];
NSString *phoneAppVersion = [dicphone objectForKey:@"CFBundleShortVersionString"];
NSArray *results = [dic objectForKey:@"results"];
// 获取当前的版本号
NSString *currentAppVersion = [[results objectAtIndex:0] objectForKey:@"version"];
self.currentVerson = currentAppVersion;
// 跟新地址
NSString *trackViewUrl = [[results objectAtIndex:0] objectForKey:@"trackViewUrl"];
self.trackViewUrl = trackViewUrl;
NSArray *arrayPhoneVersion = [phoneAppVersion componentsSeparatedByString:@"."];
NSArray *arrayCurrentVersion = [currentAppVersion componentsSeparatedByString:@"."];
// 判断版本号
[self judgeVersionWithPhoneArray:arrayPhoneVersion CurrentArray:arrayCurrentVersion];
});
}
else {
NSLog(@"网上获取版本号出错");
}
}];
[task resume];
}
#pragma mark - 判断版本号的大小
- (void)judgeVersionWithPhoneArray:(NSArray *)phoneArray CurrentArray:(NSArray *)currentArray
{
BOOL judge = NO;
// 一般的版本号都是三位
for (int i = 0; i < 3; i++) {
NSInteger phoneverson = [[phoneArray objectAtIndex:i] integerValue];
NSInteger currentversion = [[currentArray objectAtIndex:i] integerValue];
// 说明有新版本
if (currentversion > phoneverson) {
judge = YES;
break;
}
}
// 说明发现新的版本
if (judge == YES) {
NSLog(@"说明有新版本");
// 提示更新
[self createAlertWithTrackViewUrl];
}
else {
NSLog(@"说明没有新版本");
}
}
#pragma mark - 创建版本下载提示
- (void)createAlertWithTrackViewUrl
{
NSString *message = [NSString stringWithFormat:@"发现新版本(%@),是否更新", self.currentVerson];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:message delegate:self cancelButtonTitle:@"稍后" otherButtonTitles:@"确定", nil];
[alert show];
}
#pragma mark - UIAlertView代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
NSURL *url = [NSURL URLWithString:self.trackViewUrl];
[[UIApplication sharedApplication] openURL:url];
}
}