最近項目里面要添加一個提醒更新功能籽懦,在網(wǎng)上查了下崩哩,代碼如下:
//時間間隔一小時
NSDate *currentDate = [NSDate date];
NSDate *userLastOpenDate =[[NSUserDefaults standardUserDefaults] objectForKey:@"AppTimeLastOpenDate"];
NSTimeInterval timeBetween = [currentDate timeIntervalSinceDate:userLastOpenDate];
if ((timeBetween / 60 / 60) <= 1) {
return;
}else{
[[NSUserDefaults standardUserDefaults] setObject:currentDate forKey:@"AppTimeLastOpenDate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NSString *nowVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
NSString *query = [NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@", appID];
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
NSArray *configData = [results valueForKey:@"results"];
NSString *version = @"";
for (id config in configData)
{
version = [config valueForKey:@"version"];
}
if ([version floatValue] > [nowVersion floatValue]) {
UIAlertController *alertController=[UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"新版本%@已發(fā)布",version] message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action=[UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/chuang-youapp/id%@?mt=8",appID]]];
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
}];
[alertController addAction:action];
[alertController addAction:cancel];
[self presentViewController:alertController animated:YES completion:nil];
}
整體思路就是:
1档悠、拿當(dāng)前版本的版本號跟AppStore上的版本號去比較思喊,如果當(dāng)前版本比AppStore上的要低壁酬,說明有新版本已經(jīng)更新,彈出提醒框恨课;
2舆乔、用戶點擊更新,通過URL跳轉(zhuǎn)到AppStore上去更新剂公;
3希俩、為了更好的體驗效果添加一個時間間隔,不會在用戶每次使用的時候都會提示有更新纲辽。