.h文件
@interface CheckUpdateTool : NSObject
/**
從蘋果服務器獲取版本
*/
+ (void)getVersionFromServer;
@end
.m文件
#import "CheckUpdateTool.h"
#import <UIKit/UIKit.h>
#define APPLEID @"AppleID" /// App 在蘋果開發(fā)者中生成的Apple ID
@implementation CheckUpdateTool
+ (void)getVersionFromServer {
// 取出本地的版本號
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString *app_build = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
/// 當前版本
double currentVersion = [app_build stringByReplacingOccurrencesOfString:@"." withString:@""].doubleValue;
//1.創(chuàng)建會話對象
NSURLSession *session = [NSURLSession sharedSession];
//2.根據(jù)會話對象創(chuàng)建task
NSString *requestStr = [@"http://itunes.apple.com/cn/lookup?id=" stringByAppendingString:APPLEID];
NSURL *url = [NSURL URLWithString:requestStr];
//3.創(chuàng)建可變的請求對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//4.修改請求方法為POST
request.HTTPMethod = @"POST";
//5.設置請求體
request.HTTPBody = [@"" dataUsingEncoding:NSUTF8StringEncoding];
//6.根據(jù)會話對象創(chuàng)建一個Task(發(fā)送請求)
/*
第一個參數(shù):請求對象
第二個參數(shù):completionHandler回調(請求完成【成功|失敗】的回調)
data:響應體信息(期望的數(shù)據(jù))
response:響應頭信息馆蠕,主要是對服務器端的描述
error:錯誤信息,如果請求失敗惊奇,則error有值
*/
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable responseObject, NSError * _Nullable error) {
if (data) {
//返回數(shù)據(jù)的處理邏輯
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSArray *appInfos = response[@"results"];
if (!appInfos || appInfos.count <= 0) {
return;
}
NSDictionary *appInfo = appInfos[0];
//服務器版本
double serverVersion = [appInfo[@"version"] stringByReplacingOccurrencesOfString:@"." withString:@""].doubleValue;
/// 服務器版本大于本地版本
if (serverVersion > currentVersion) {
UIAlertController *al = [UIAlertController alertControllerWithTitle:@"發(fā)現(xiàn)新版本" message:appInfo[@"releaseNotes"] preferredStyle:UIAlertControllerStyleAlert];
[al addAction:[UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
/// 前往更新
NSString *str = [[NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id"] stringByAppendingString:APPLEID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}]];
[al addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil]];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:al animated:YES completion:nil];
}
}
}];
//7.執(zhí)行任務
[dataTask resume];
}
@end