iOS开发笔记-78: swift4.0 app检测更新

/ Mac / 没有评论 / 1216浏览

iOS开发笔记-78: swift4.0 app检测更新

oc版本的检测更新

#pragma mark - 检测版本更新
- (void)updateApp
{

    NSString *appID;
    appID = @"1235965473";

    NSString *appUrl = @"http://itunes.apple.com/lookup?id=";
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", appUrl, appID];

    JJHttpRequestManage *manage = [JJHttpRequestManage defaultManager];
    [manage GetUrl:urlStr parameters:nil succeessWithJsonResult:^(NSURLSessionDataTask *task, id responseObject) {
        JJLog(@"appstore data :%@",responseObject);

        NSArray *resultArray = [responseObject objectForKey:@"results"];

        if (![resultArray count]) {
            JJLog(@"error : resultArray == nil");
            return;
        }
        NSDictionary *infoDict = [resultArray objectAtIndex:0];
        //获取服务器上应用的最新版本号
        NSString *updateVersion = infoDict[@"version"];
        NSString *trackName = infoDict[@"trackName"];
        NSString *note = [infoDict objectForKey:@"releaseNotes"];

        _trackViewUrl = infoDict[@"trackViewUrl"];

        //获取当前设备中应用的版本号
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"] ;

        //判断两个版本是否相同
        if ([updateVersion compare:currentVersion options:NSNumericSearch] == NSOrderedDescending) {
            NSString *titleStr = [NSString stringWithFormat:@"检查更新:%@", trackName];

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:titleStr message:note delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"升级", nil];

            alert.tag = 999;
            [alert show];
        }
    } failureConnectingNet:^(NSURLSessionDataTask *task, NSError *error) {
        JJLog(@"error :%@",error);

    }];
}

swift

///检查版本更新
func checkAppUpdate() {

  APIRequest.getUserConfig(codes: "s_app_version_no_ios,u_app_download_ios,s_app_version_no_desc_ios") { 
    (JSONData) in
    let data = JSONData as! JSON
    let version = data["s_app_version_no_ios"]["v"].stringValue
    let urlStr = data["u_app_download_ios"]["v"].stringValue
    let desc = data["s_app_version_no_desc_ios"]["v"].stringValue
    let localVer = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
    SessionManager.sharedInstance.downloadURL = urlStr
    if localVer.compare(version) == ComparisonResult.orderedAscending {
      //升级
      DispatchQueue.main.async {
        let simpleHUD = UpdateVersionController(nibName: "UpdateVersionController", bundle: nil)
        guard let vc = Toolkit.getCurrentViewController() else {
          return
        }
        simpleHUD.modalPresentationStyle = .overCurrentContext
        vc.present(simpleHUD, animated: false) {
          simpleHUD.updateLabel.text = desc
        }
        simpleHUD.dismissHandler = {
          if let url = URL(string: urlStr) {
            UIApplication.shared.openURL(url)
          }
        }
      }
    }
  }
}