我们开发的APP供用户使用,当我们向AppStore提交了新的版本,并且审核通过,我们需要向用户提示有新的更新供用户下载,检测更新的方法有很多种,也有第三方框架可以使用,这里介绍一种我常用的方法,我们在程序启动后需要的位置调用它就可以了。
#pragma mark - 检测更新
-(void)checkUpdate
{
NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", APP_URL]];
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
NSMutableData *httpRequestData = [NSMutableData data];
[mutableRequest setHTTPMethod:@"POST"];
[mutableRequest setHTTPBody:httpRequestData];
[mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[mutableRequest setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[httpRequestData length]] forHTTPHeaderField:@"Content-Length"];
NSError *error;
NSURLResponse *response;
NSData *resultData = [NSURLConnection sendSynchronousRequest:mutableRequest returningResponse:&response error:&error];
if (resultData !=nil) {
NSArray *infoArray = [[NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableContainers error:&error] objectForKey:@"results"];
if (infoArray.count != 0) {
NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
NSString *latestVersion = [releaseInfo objectForKey:@"version"];
if ([[self stringDeleteString:latestVersion] integerValue] >[[self stringDeleteString:appVersion] integerValue]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:[NSString stringWithFormat:@"%@",[releaseInfo objectForKey:@"releaseNotes"] ] delegate:self cancelButtonTitle:@"以后再说" otherButtonTitles:@"现在就去", nil];
alert.tag = 10000;
[alert show];
}
}
}
}
- (NSString *) stringDeleteString:(NSString *)str{
NSMutableString *str1 = [NSMutableString stringWithString:str];
for (int i = 0; i < str1.length; i++) {
unichar c = [str1 characterAtIndex:i];
NSRange range = NSMakeRange(i, 1);
if (c == '.') {
[str1 deleteCharactersInRange:range];
--i;
}
}
NSString *newstr = [NSString stringWithString:str1];
return newstr;
}
当有新的版本时,我们用一个UIAlertView或UIAlertController提示用户更新。
- (NSString *) stringDeleteString:(NSString *)str
此方法是用来消除掉我们获取到的版本号中间的"."。这样我们就容易比较两个版本号的大小了。