iOS 版本更新检查

时间:2022-01-01 23:42:32

#pragma mark ----------------------------------

#pragma mark -- 检测版本更新

-(void)onCheckVersion

{

NSDictionary *infoDic = [[NSBundlemainBundle] infoDictionary];

NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];//CFBundleVersion

NSString *URL = @"http://itunes.apple.com/lookup?id=你的appId";

NSMutableURLRequest *request = [[NSMutableURLRequestalloc] init];

[request setURL:[NSURL URLWithString:URL]];

[request setHTTPMethod:@"POST"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

if (data == nil) {

return ;

}

NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:nil];

NSArray *infoArray = [dic objectForKey:@"results"];

if ([infoArray count]) {

NSDictionary *releaseInfo = [infoArray objectAtIndex:0];

NSString *lastVersion = [releaseInfo objectForKey:@"version"];

//测试数据

//        currentVersion = @"1.1";

//        lastVersion = @"1.1.1";

//版本号处理并比较大小

NSMutableArray *lastVersionArr = [NSMutableArray arrayWithArray:[lastVersion componentsSeparatedByString:@"."]];

NSMutableArray *currentVersionArr = [NSMutableArray arrayWithArray:[currentVersion componentsSeparatedByString:@"."]];

BOOL haveNewVersion = NO;

//比较数组长度 不相等则 补零至相等

if (lastVersionArr.count > currentVersionArr.count) {

for (int i = 0 ; i < lastVersionArr.count - currentVersionArr.count; ++i) {

[currentVersionArr addObject:@"0"];

}

}else if (lastVersionArr.count < currentVersionArr.count){

for (int i = 0 ; i < currentVersionArr.count - lastVersionArr.count; ++i) {

[lastVersionArr addObject:@"0"];

}

}

//比较大小

for (int i = 0 ; i < currentVersionArr.count; ++i) {

if ([lastVersionArr[i] integerValue] > [currentVersionArr[i] integerValue]) {

haveNewVersion = YES;

[SettingsManager shareInstance].hasNewVersion = YES;

break;

}else if ([lastVersionArr[i] integerValue] < [currentVersionArr[i] integerValue])

{

haveNewVersion = NO;

[SettingsManager shareInstance].hasNewVersion = NO;

break;

}

}

if (haveNewVersion) {

UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:NSLocalizedString(@"更新", nil) message:[releaseInfo  objectForKey:@"releaseNotes"] delegate:selfcancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"前往更新", nil), nil];

alert.tag = 10000;

[alert show];

}

}

}];

}

#pragma mark - AertView delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

if (alertView.tag == 10000) {

if (buttonIndex == 1) {

[[UIApplicationsharedApplication] openURL:[NSURLURLWithString:@"你的App下载地址"]];

}

}

}