本文網(wǎng)址鏈接:http://www.codes51.com/article/detail_957490_2.html
一個老項目沒有集成自動檢測及提示用戶更新新版本的功能,自己在網(wǎng)上查資料搗鼓出自己的方法,可能比較粗陋,希望大家多多指導,我們的項目的版本號是X.X.X的格式,所以直接把字符串轉換成float類型的值無效,自己先將字符串做了處理,后來轉成float類型后對版本做比較,以下貼上代碼
#pragma mark - 檢查版本更新
- (void)checkNewVersion {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:APP_URL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { // 請求成功
// 字典接收請求到的JSon
NSDictionary *responseDict = [NSDictionary dictionaryWithDictionary:responseObject];
// 解析請求到的JSon
NSArray *results = [responseDict objectForKey:@"results"];
NSDictionary *finalDict = [results firstObject];
// 獲取APP下載地址
NSString *trackViewUrl = [finalDict objectForKey:@"trackViewUrl"];
updateUrl = [NSURL URLWithString:trackViewUrl];
// 獲取官網(wǎng)APP的版本號
NSString *str1 = [finalDict objectForKey:@"version"];
NSString *version1 = [str1 substringFromIndex:2];
// 將版本號字符串轉換成float類型
float newVersion = [version1 floatValue];
// 獲取本地項目版本號
// 拿到項目的infoPlist文件中所有內容
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
// 獲取到當前工程版本號
NSString *str2 = [infoDict objectForKey:@"CFBundleVersion"];
NSString *version2 = [str2 substringFromIndex:2];
// 將版本號字符串轉換成float類型
float localVersion = [version2 floatValue];
// 對比兩處版本號
if (newVersion > localVersion) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"有新版本可用,請安裝更新" delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil];
alert.tag = 1;
[alert show];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {// 請求失敗
// 返回請求失敗的原因
NSLog(@"NSError:%@", error);
}];
}
以下是UIAlertView的代理方法,用于監(jiān)聽用戶的點擊后做響應,跳轉到商店下載頁面
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.tag == 1) {
// 跳轉到下載頁面
[[UIApplication sharedApplication] openURL:updateUrl];
}
}