系统启动时,在AppDelegate.application方法中,初始化完友盟、SharedSDK和环信之后,就开始检查版本更新了。这时检查版本更新实际了有些早,因为如果需要进行版本灰度发布时,需要知道用户的ID,在此处检查版本更新则不能实现基于用户的灰度版本发布。
系统先初始化HTTP请求需要的类对象:
_dtHttpHelper = [[DTHttpHelper alloc]init];
_dtHttpHelper.delegate = self;
其中将HTTP访问类的回调代理设置为本类,就是当HTTP请求成功,有合法数据返回时,会调用本类定义的回调函数来进行处理。
AppDelegate.application中检查版本更新的代码如下所示:
- (void)checkVersionByServer{
NSString *urlStr = [NSString stringWithFormat:@"%@getVersion&roleId=2&platform=%@",ServerIPCMD,@"IOS"];
[_dtHttpHelper getDataFormServerWithUrlString:urlStr andCmdType:DTgetVersion];
}
当HTTP请求成功后,将调用如下的回调函数进行数据处理:
- (void)DTHttpHelperSuccessWithDataSource:(NSDictionary *)dataSource andCmdType:(NSInteger)cmdType{
if (cmdType == DTgetVersion)
{
if ([dataSource objectForKey:KStatus]!= [NSNull null] && [[dataSource objectForKey:KStatus] isEqualToString:KOk])
{
if([[dataSource objectForKey:KStatus] isEqualToString:KOk])
{
if ([dataSource objectForKey:@"version"])
{
NSString *newVersion = [dataSource objectForKey:@"version"];
NSString *curVersion = [[NSUserDefaults standardUserDefaults]objectForKey:KCurVersion];
long long newVersionNum = [[NSString stringWithFormat:@"%@",[dataSource objectForKey:@"flagNum"]]longLongValue];
long long curVersionNum = [[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:KCurVersionNum]]longLongValue];
if (newVersionNum > curVersionNum)
{
_downloadUrl = [NSString stringWithFormat:@"%@",[dataSource objectForKey:@"downloadUrl"]];
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:KHaveNewVersion];
[[NSUserDefaults standardUserDefaults]setObject:newVersion forKey:KNewVersion];
[[NSUserDefaults standardUserDefaults]synchronize];
NSString *isForced = [NSString stringWithFormat:@"%@",[dataSource objectForKey:@"isForced"]];
UIAlertView *versionAlert = nil;
if ([isForced isEqualToString:@"1"])
{
versionAlert = [[UIAlertView alloc]initWithTitle:@"请更新最新版本,否则无法使用。" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
}
else
{
versionAlert = [[UIAlertView alloc]initWithTitle:@"发现新版本,是否更新?" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
}
versionAlert.tag = 10001;
[versionAlert show];
}
}
}
}
}
}
版本号采用一个整数来表示,数值越大代表版本越新,分为强制更新和普通更新,强制更新如果用户不更新则不允许用户继续使用。
如果是强制更新时,消息框中只有一个确定按钮,而如果不是强制更新时,消息框中有确定和取消两个按钮,如果用户点取消按钮时,则直接向下执行,不进行版本更新操作。如果用户点击确定按钮,会调用AppDelegate中的回调函数:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
if (alertView.tag == 10001)
{
if (buttonIndex == 0)
{
BOOL downloadApp = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_downloadUrl]];
[self exitApplication];
}
}
如果用户点击的是版本提示的消息框,并且按的是确定按钮,则执行版本更新操作。