iOS 自动提醒更新

作者: 在这蓝色天空下 | 来源:发表于2016-10-24 16:54 被阅读134次

    最近项目里面要添加一个提醒更新功能,在网上查了下,代码如下:

    //时间间隔一小时
        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:@"新版本%@已发布",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、拿当前版本的版本号跟AppStore上的版本号去比较,如果当前版本比AppStore上的要低,说明有新版本已经更新,弹出提醒框;
    2、用户点击更新,通过URL跳转到AppStore上去更新;
    3、为了更好的体验效果添加一个时间间隔,不会在用户每次使用的时候都会提示有更新。

    相关文章

      网友评论

        本文标题:iOS 自动提醒更新

        本文链接:https://www.haomeiwen.com/subject/kbuluttx.html