iOS 自动检测版本更新APP

2018-03-12  本文已影响44人  过眼云烟1102

一、实现思路

/** 实现思路

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

  2.拿到AppStore项目版本号

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

 */

//一定要先配置自己项目在商店的APPID,配置完最好在真机上运行才能看到完全效果哦

#define STOREAPPID @"1234567890"

二、代码实现

//检测app更新

-(void)updateApp

{

 //1.先获取当前工程项目版本号

 NSDictionary *infoDic = [[NSBundlemainBundle]infoDictionary];

 NSString *currentVersion = infoDic[@"CFBundleShortVersionString"];

 //2.从网络获取appStore版本号

 NSError *error;

 NSData *response = [NSURLConnectionsendSynchronousRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:[NSStringstringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",STOREAPPID]]]returningResponse:nilerror:nil];

 //2.1没有内容

 if (response == nil) {

 NSLog(@"你没有连接网络哦");

 return;

    }

 //3.序列化解析

 NSDictionary *appInfoDic = [NSJSONSerializationJSONObjectWithData:responseoptions:NSJSONReadingMutableLeaveserror:&error];

 //3.1数据错误

 if (error) {

 NSLog(@"hsUpdateAppError:%@",error);

 return;

    }

 //3.2字典解析

 NSArray *array = appInfoDic[@"results"];

 NSDictionary *dic = array[0];

 NSString *appStoreVersion = dic[@"version"];

 //打印版本号

 NSLog(@"当前版本号:%@\n商店版本号:%@",currentVersion,appStoreVersion);

 //4.当前版本号小于商店版本号,就更新

 if([currentVersion floatValue] < [appStoreVersion floatValue])

    {

 UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"版本有更新"  message:[NSStringstringWithFormat:@"检测到新版本(%@),是否更新?",appStoreVersion] delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"更新",nil];

[alert show];

}else{

 NSLog(@"检测到不需要更新");

    }

}

上一篇 下一篇

猜你喜欢

热点阅读