1.一定要先配置自己項(xiàng)目在商店的APPID(從蘋(píng)果開(kāi)發(fā)者中心登錄自己的賬號(hào)可看),配置完最好在真機(jī)上運(yùn)行才能看到完全效果哦!
define STOREAPPID @"1104867082" // 宏定義APPID
/**
-
天朝專用檢測(cè)app更新
一句代碼實(shí)現(xiàn)檢測(cè)更新,很簡(jiǎn)單哦 (需要在viewDidAppear完成時(shí)框都,再調(diào)用改方法帚桩。不然 在網(wǎng)速飛快的時(shí)候工闺,會(huì)出現(xiàn)一個(gè)bug鸵贬,就是當(dāng)前控制器viewDidLoad調(diào)用的話甫菠,可能當(dāng)前視 圖還沒(méi)加載完畢就需要推出UIAlertAction)
*/
-(void)hsUpdateApp
{
//2先獲取當(dāng)前工程項(xiàng)目版本號(hào)
NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];//3從網(wǎng)絡(luò)獲取appStore版本號(hào)
NSError *error;
NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",STOREAPPID]]] returningResponse:nil error:nil];
if (response == nil) {
NSLog(@"你沒(méi)有連接網(wǎng)絡(luò)哦");
return;
}
NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(@"hsUpdateAppError:%@",error);
return;
}
// NSLog(@"%@",appInfoDic);
NSArray *array = appInfoDic[@"results"];
NSDictionary *dic = array[0];
NSString *appStoreVersion = dic[@"version"];
//打印版本號(hào)
NSLog(@"當(dāng)前版本號(hào):%@\n商店版本號(hào):%@",currentVersion,appStoreVersion);
//設(shè)置版本號(hào)
currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
if (currentVersion.length==2) {
currentVersion = [currentVersion stringByAppendingString:@"0"];
}else if (currentVersion.length==1){
currentVersion = [currentVersion stringByAppendingString:@"00"];
}
appStoreVersion = [appStoreVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
if (appStoreVersion.length==2) {
appStoreVersion = [appStoreVersion stringByAppendingString:@"0"];
}else if (appStoreVersion.length==1){
appStoreVersion = [appStoreVersion stringByAppendingString:@"00"];
}//4當(dāng)前版本號(hào)小于商店版本號(hào),就更新
if([currentVersion floatValue] < [appStoreVersion floatValue])
{
UIAlertController *alercConteoller = [UIAlertController alertControllerWithTitle:@"版本有更新" message:[NSString stringWithFormat:@"檢測(cè)到新版本(%@),是否更新?",dic[@"version"]] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//此處加入應(yīng)用在app store的地址,方便用戶去更新,一種實(shí)現(xiàn)方式如下
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/id%@?ls=1&mt=8", STOREAPPID]];
[[UIApplication sharedApplication] openURL:url];
}];
UIAlertAction *actionNo = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}]; [alercConteoller addAction:actionYes]; [alercConteoller addAction:actionNo]; [self presentViewController:alercConteoller animated:YES completion:nil];
}else{
NSLog(@"版本號(hào)好像比商店大噢!檢測(cè)到不需要更新");
}
}