iOS 开发笔记 - 开发中如何实现自动检测更新APP

来源:互联网 发布:韩国bj 知乎 编辑:程序博客网 时间:2024/06/13 15:23

自动检测更新实现逻辑:

先上github地址:https://github.com/wolfhous/HSUpdateApp

1,获取当前项目APP版本号

2,拿到AppStore项目版本号

3,对比版本号,实现更新功能

一点源码:

复制代码
 1 /** 2  *  天朝专用检测app更新 3  */ 4 -(void)hsUpdateApp 5 { 6     //2先获取当前工程项目版本号 7     NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary]; 8     NSString *currentVersion=infoDic[@"CFBundleShortVersionString"]; 9     10     //3从网络获取appStore版本号11     NSError *error;12     NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",STOREAPPID]]] returningResponse:nil error:nil];13     if (response == nil) {14         NSLog(@"你没有连接网络哦");15         return;16     }17     NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];18     if (error) {19         NSLog(@"hsUpdateAppError:%@",error);20         return;21     }22 //    NSLog(@"%@",appInfoDic);23     NSArray *array = appInfoDic[@"results"];24     NSDictionary *dic = array[0];25     NSString *appStoreVersion = dic[@"version"];26     //打印版本号27     NSLog(@"当前版本号:%@\n商店版本号:%@",currentVersion,appStoreVersion);28     //4当前版本号小于商店版本号,就更新29     if([currentVersion floatValue] < [appStoreVersion floatValue])30     {31         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本有更新" message:[NSString stringWithFormat:@"检测到新版本(%@),是否更新?",appStoreVersion] delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"更新",nil];32         [alert show];33     }else{34         NSLog(@"版本号好像比商店大噢!检测到不需要更新");35     }36 37 }
复制代码
复制代码
 1 - (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 2 { 3     //5实现跳转到应用商店进行更新 4     if(buttonIndex==1) 5     { 6         //6此处加入应用在app store的地址,方便用户去更新,一种实现方式如下: 7         NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/id%@?ls=1&mt=8", STOREAPPID]]; 8         [[UIApplication sharedApplication] openURL:url]; 9     }10 }
复制代码

然后在你想检测更新的窗口实现:

1 //一句代码实现检测更新2     [self hsUpdateApp];

 附:STOREAPPID这个宏定义为你的app在商店的id号,就是一串数字,一种方法是自己登陆itunesconnect可以查看,另一种方法是百度或者google

0 0