美文网首页
iOS App 检测版本升级

iOS App 检测版本升级

作者: BerrySang | 来源:发表于2016-07-01 16:06 被阅读2390次
    更新于 2018.06.08
    好久没管过简书了😂
    注意:Apple ID 在您在appstoreconnect.apple.com网站初建App时就会生成
    或者你可以通过存储版本号到本地沙盒里面以进行比较
    再加一个Swift4版本的吧
    // MARK: --检测App版本更新
    func checkAppVersionUpdate() {
        let appStoreStr: String = "https://itunes.apple.com/lookup?id=\(app在appStore的id号)"
        
        // 这里是网络请求的方法,你可以替换成你自己写的方法,POST/GET请求都是可以的
        BSNetworkManager.shared.requestData(requestType: .POST, url: appStoreStr, param: nil, success: { (jsonDic) in
            //BSLog("json===\(jsonDic)")
            guard
                //let value = jsonDic.stringValue,
                let json = Optional(JSON(jsonDic)),
                //json["results"] 这里的json直接用网络请求返回来的json字典就可以的,可以省略上面的一步
                let storeVersion = json["results"].arrayValue.first?["version"].string
                else {
                    BSLog("无法获取到App版本信息")
                    return
            }
            //BSLog("verson == \(storeVersion)")
            
            let nativeVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
            
            let compareRes = nativeVersion.compare(storeVersion)
            if compareRes == ComparisonResult.orderedAscending { //本地版本 小于 商店版本 需要更新
                //UIApplication.shared.keyWindow
                let alertCtr = UIAlertController.init(title: "有新版本建议更新", message: nil, preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil) //取消不作处理
                let sureAction = UIAlertAction(title: "确定", style: .default, handler: { (UIAlertAction) in
                    //BSLog("跳到商店去更新")
                    UIApplication.shared.openURL(URL.init(string: "https://itunes.apple.com/cn/app/id\(app在appStore的id号)?mt=8")!)
                })
                alertCtr.addAction(cancelAction)
                alertCtr.addAction(sureAction)
                
                let window = UIWindow.init(frame: UIScreen.main.bounds)
                window.rootViewController = UIViewController()
                window.windowLevel = UIWindowLevelAlert + 1
                window.makeKeyAndVisible()
                window.rootViewController?.present(alertCtr, animated: true, completion: nil)
            }
            else if compareRes == ComparisonResult.orderedSame { //本地版本 = 商店版本
    
            }
            else if compareRes == ComparisonResult.orderedDescending { //本地版本 大于 商店版本
                
            }
            
        }) { (err) in
            
        }
    }
    

    )OC版本的 写的比较早了,

    1. 获取appStore的APP数据//获取appStore版本号
    #pragma mark -- 获取appStore的APP数据 // 获取appStore版本号
    - (void)PostpathAPPStoreVersion
    {
        // 这是获取appStore上的app的版本的url
        NSString *appStoreUrl = [[NSString alloc] initWithFormat:@"http://itunes.apple.com/lookup?id=%@",@"这里填app在appStore的id号"];
        
        
        NSURL *url = [NSURL URLWithString:appStoreUrl];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                           timeoutInterval:10];
        
        [request setHTTPMethod:@"POST"];
        
        
        NSOperationQueue *queue = [NSOperationQueue new];
        
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
            NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
            if (data) {
                
                NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
                    
                    [receiveStatusDic setValue:@"1" forKey:@"status"];
                    [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
                }else{
                    
                    [receiveStatusDic setValue:@"-1" forKey:@"status"];
                }
            }else{
                [receiveStatusDic setValue:@"-1" forKey:@"status"];
            }
            
            [self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
        }];
        
    }
    

    下面的 sender[@"version"] 就是获取的版本号 注意是String类型的

    比较之后在alertView的Delegate里处理就行了 这个写的比较早了,你可以把alertView替换成UIAlertController使用
    2 . 比较appStore的app版本号和本地的app的版本号
    -(void)receiveData:(id)sender
    {
        
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        // 手机当前APP软件版本  比如:1.0.2
        NSString *nativeVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        NSString *storeVersion  = sender[@"version"];
        
        DEBUGLog(@"本地版本号curV=%@", nativeVersion);
        DEBUGLog(@"商店版本号appV=%@", sender[@"version"]);
        
    
        NSComparisonResult comparisonResult = [nativeVersion compare:storeVersion options:NSNumericSearch];
        
        //NSOrderedSame相同 NSOrderedAscending = -1L表示升序;  NSOrderedDescending = +1 表示降序
        UIAlertView *alertv = [[UIAlertView alloc]initWithTitle:@"有新版本是否更新" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        switch (comparisonResult) {
            case NSOrderedSame:
                DEBUGLog(@"本地版本与商店版本号相同,不需要更新");
                break;
            case NSOrderedAscending:
                DEBUGLog(@"本地版本号 < 商店版本号相同,需要更新");
                [alertv show];
                break;
            case NSOrderedDescending:
                DEBUGLog(@"本地版本号 > 商店版本号相同,不需要更新");
                break;
            default:
                break;
        }
        
    }
    

    顺便把检测可能用到的其他信息也贴一下吧

    pragma mark --检测版本等信息

    - (void)PhoneAppVersionInfomations{
        NSString* identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString] ;
        DEBUGLog(@"手机序列号: %@",identifierNumber);
        //手机别名: 用户定义的名称
        
        NSString* userPhoneName = [[UIDevice currentDevice] name];
        DEBUGLog(@"手机别名: %@", userPhoneName);
        //设备名称
        
        NSString* deviceName = [[UIDevice currentDevice] systemName];
        DEBUGLog(@"设备名称: %@",deviceName );
        //手机系统版本
        
        NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
        DEBUGLog(@"手机系统版本: %@", phoneVersion);
        //手机型号
        
        NSString* phoneModel = [[UIDevice currentDevice] model];
        DEBUGLog(@"手机型号: %@",phoneModel );
        
        //地方型号  (国际化区域名称)
        NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
        DEBUGLog(@"国际化区域名称: %@",localPhoneModel );
        
        
        
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        // 当前应用名称
        NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
        DEBUGLog(@"当前应用名称:%@",appCurName);
        
        // 当前应用软件版本  比如:1.0.1
        NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        DEBUGLog(@"当前应用软件版本:%@",appCurVersion);
        
        // 当前应用版本号码   int类型
        NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
        DEBUGLog(@"当前应用版本号码:%@",appCurVersionNum);
        
    }
    

    相关文章

      网友评论

          本文标题:iOS App 检测版本升级

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