iOS添加自动更新的代码

时间:2023-03-09 05:10:10
iOS添加自动更新的代码
- (void)versionUpdate{

    //获得当前发布的版本
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ), ^{ //耗时的操作--获取某个应用在AppStore上的信息,更改id就行
__weak LoginViewController *weakSelf = self;
NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/cn/lookup?id=1108288793"] encoding:NSUTF8StringEncoding error:nil];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *version = [[[dic objectForKey:@"results"]firstObject]objectForKey:@"version"]; NSString *updateInfo = [[[dic objectForKey:@"results"]firstObject]objectForKey:@"releaseNotes"];
//NSString *updateURL = [[[dic valueForKey:@"results"] firstObject] objectForKey:@""]; //获得当前版本
NSString *currentVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"]; dispatch_async(dispatch_get_main_queue(), ^{
//更新界面
if ( version &&![version isEqualToString:currentVersion]) {
//有新版本
NSString *message = [NSString stringWithFormat:@"有新版本发布啦!\n%@",updateInfo];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { }];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSString *url = @"https://itunes.apple.com/cn/app/rich-products/id1108288793?mt=8&uo=4"; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}]; [alertController addAction:action1];
[alertController addAction:action2]; [weakSelf presentViewController:alertController animated:YES completion:nil];
}else{
//已是最高版本
NSLog(@"已是最高版本");
} }); }); }

记得http://itunes.apple.com/cn/lookup?id=1108288793,这中间的这个CN不能掉了,不然返回的JSON数组为空。