.h文件
@interface CheckUpdateTool : NSObject
/**
从苹果服务器获取版本
*/
+ (void)getVersionFromServer;
@end
.m文件
#import "CheckUpdateTool.h"
#import <UIKit/UIKit.h>
#define APPLEID @"AppleID" /// App 在苹果开发者中生成的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.创建会话对象
NSURLSession *session = [NSURLSession sharedSession];
//2.根据会话对象创建task
NSString *requestStr = [@"http://itunes.apple.com/cn/lookup?id=" stringByAppendingString:APPLEID];
NSURL *url = [NSURL URLWithString:requestStr];
//3.创建可变的请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//4.修改请求方法为POST
request.HTTPMethod = @"POST";
//5.设置请求体
request.HTTPBody = [@"" dataUsingEncoding:NSUTF8StringEncoding];
//6.根据会话对象创建一个Task(发送请求)
/*
第一个参数:请求对象
第二个参数:completionHandler回调(请求完成【成功|失败】的回调)
data:响应体信息(期望的数据)
response:响应头信息,主要是对服务器端的描述
error:错误信息,如果请求失败,则error有值
*/
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable responseObject, NSError * _Nullable error) {
if (data) {
//返回数据的处理逻辑
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:@"发现新版本" 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.执行任务
[dataTask resume];
}
@end