• Ionic
  • ionic2/3 热更新

    Ionic 3个月前 486次点击 来自 Ionic

    下载安装插件

    ionic cordova plugin add cordova-hot-code-push-plugin
    npm install -g cordova-hot-code-push-cli
    
    

    热更新作为插件集成

    import { Injectable } from '@angular/core';
    import { LoadingController, AlertController, Platform } from 'ionic-angular';
    import { Http } from '@angular/http';
    @Injectable()
    export class CHCPService {
      chcp: any;
      public updateText = '正在下载更新包';
      public showUpdate: boolean = false;
      public interval: any;
      public url: any;
      constructor(
        public loadingCtrl: LoadingController,
        public alertCtrl: AlertController,
        public http: Http,
        public platform: Platform) {
    
      }
    
      public initCHCP(chcp): void {
        this.chcp = chcp;
        let TIME_IN_MS = 3000;
        // alert(chcp);
        //console.log('chcp check', window.chcp);
        if (this.platform.is("android")) {
          console.log('android');
          this.url = 'https://5222427a.ngrok.io/chcp.json'
        }
        if (this.platform.is("ios")) {
          this.url = 'https://5222427a.ngrok.io/chcp.json';
          console.log('ios')
        }
    
        this.initialize();
        console.log(this.url);
        this.updateText="初始化";
        this.interval = setInterval(() => {
          // this.showUpdate;
          // this.updateText;
          console.log(this.updateText);
        }, TIME_IN_MS);
    
      }
      onShowUpdate() {
        this.showUpdate = true;
      }
      hiddenUpdate() {
        this.showUpdate = false;
      }
      //内壳外壳,更新
      initialize() {
        this.bindEvents();
      }
      bindEvents() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
        //当插件无法从服务器加载更新时发送。错误详细信息附加到事件。用于外壳更新
        document.addEventListener('chcp_updateLoadFailed', this.onUpdateLoadError.bind(this), false);
        //当新版本成功加载并准备安装时发送
        document.addEventListener('chcp_updateIsReadyToInstall', this.onReadyToInstall.bind(this), false);
        //在即将安装更新时发送。
        document.addEventListener('chcp_beforeInstall', this.onBeforeInstall.bind(this), false);
        //成功安装更新
        document.addEventListener('chcp_updateInstalled', this.onInstalle.bind(this), false);
        //安装更新失败时
        document.addEventListener('chcp_updateInstallFailed', this.installError.bind(this), false);
        //当用户手机存储卡不够用时
        document.addEventListener('chcp_assetsInstallationError', this.onInstallationError.bind(this), false);
      }
    
      // deviceready Event Handler
      onDeviceReady() {
         this.chcp.getVersionInfo((error, data) => {
          if (error) {
            console.log(error)
          }
          console.log(data.currentWebVersion);
          let currentWebVersion = data.currentWebVersion;
          let release;
          this.http.get(this.url).subscribe((data) => {
            release = data.json();
            console.log(release.release);
            if (release.release != currentWebVersion) {
              this.interval;
              this.onShowUpdate();
              this.chcp.fetchUpdate(this.fetchUpdateCallback.bind(this));
            }
          });
        });
    
      }
      installError() {
        console.log('安装更新失败')
      }
      installationCallback(error) {
        if (error) {
          //console.log('Failed to install the update with error code: ' + error.code);
          //console.log(error.description);
          let alert = this.alertCtrl.create({
            title: '更新不成功',
            message: '安装更新包过程中发生错误,请重启app再次尝试升级',
            buttons: [
              {
                text: '明白了',
                role: 'cancel',
                handler: () => { }
              }
            ]
          });
          alert.present();
    
        } else {
          console.log('Update installed!');
        }
      }
    
      fetchUpdateCallback(error, data) {
        console.log('发生错误,错误代码: ' + error.code);
        if (error.code === -3 || error.code === -4) {
          this.hiddenUpdate();
          clearInterval(this.interval);
          var dialogMessage = '下载失败,去App store下载最新版';
          this.chcp.requestApplicationUpdate(dialogMessage);
        }
        // console.log(error.description);
        //error.code=2没有更新,error.code=-17下载正在进行
        if (error) {
          //loading.dismiss();
          //console.log('没有检测到任何文件更新')
          //console.log(error.description);
    
          this.hiddenUpdate();
          setTimeout(() => {
            clearInterval(this.interval)
          }, 100)
    
        }
        console.log('文件加载中');
    
    
      }
      //外壳更新
      onUpdateLoadError(eventData) {
        var error = eventData.detail.error;
        if (error && error.code == this.chcp.error.APPLICATION_BUILD_VERSION_TOO_LOW) {
          //console.log('Native side update required');
          var dialogMessage = '发现新版本,即刻下载安装.';
          this.chcp.requestApplicationUpdate(dialogMessage);
        }
      }
      userWentToStoreCallback() { }
      userDeclinedRedirectCallback() { }
      //当新版本成功加载并准备安装时发送
      onReadyToInstall() {
        //console.log('正在安装更新');
        this.updateText = '正在安装更新'
        this.chcp.installUpdate(this.installationCallback.bind(this));
      }
      //安装即将开始
      onBeforeInstall() {
        this.updateText = '即将开始升级'
      }
      //安装更新成功
      onInstalle() {
        //console.log('升级完成')
        this.updateText = '升级完成'
        this.hiddenUpdate();
        setTimeout(() => {
          clearInterval(this.interval)
        }, 100)
      }
      //存储卡不够用时提醒用户
      onInstallationError() {
        //console.log('存储空间不够升级')
        let alert = this.alertCtrl.create({
          title: '存储错误',
          message: '您的手机存储不足,无法下载更新包',
          buttons: [
            {
              text: '明白了',
              role: 'cancel',
              handler: () => { }
            }
          ]
        });
        alert.present();
      }
    
    }
    
    

    集成编译错误处理

    cordova-hot-code-push-local-dev-addon插件有4个问题
    一个是Generator类不能用,使用xcode自己的fix修复就可以了。

    或者Update SocketIOClientConfiguration.swift 中的28行为

    public typealias Generator = Array<SocketIOClientOption>.Iterator
    

    二个是swift版本问题,在build setting里面修改swift language的版本为3.2

    三个是将plugins目录中该插件的script/lib/swiftHelper.js中loadProjectFile函数的问题


    function loadProjectFile() { var platform_ios, projectFile; try { // try pre-5.0 cordova structure platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms')['ios']; projectFile = platform_ios.parseProjectFile(iosPlatformPath); } catch (e) { try { // let's try cordova 5.0 structure platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms/ios'); projectFile = platform_ios.parseProjectFile(iosPlatformPath); } catch (e) { // Then cordova 7.0 var project_files = context.requireCordovaModule('glob').sync(path.join(iosPlatformPath, '*.xcodeproj', 'project.pbxproj')); if (project_files.length === 0) { throw new Error('does not appear to be an xcode project (no xcode project file)'); } var pbxPath = project_files[0]; var xcodeproj = context.requireCordovaModule('xcode').project(pbxPath); xcodeproj.parseSync(); projectFile = { 'xcode': xcodeproj, write: function () { var fs = context.requireCordovaModule('fs'); var frameworks_file = path.join(iosPlatformPath, 'frameworks.json'); var frameworks = {}; try { frameworks = context.requireCordovaModule(frameworks_file); } catch (e) {} fs.writeFileSync(pbxPath, xcodeproj.writeSync()); if (Object.keys(frameworks).length === 0) { // If there is no framework references remain in the project, just remove this file context.requireCordovaModule('shelljs').rm('-rf', frameworks_file); return; } fs.writeFileSync(frameworks_file, JSON.stringify(this.frameworks, null, 4)); } }; } } return projectFile; }

    最后一个是unknown type name ‘SocketIOClient’

    在Build Settins中查看Swift Compiler中生成的Objective-C Generated Interface Header Name 中的==MyApp-Swift.h==,把这个头文件的名字加到HCPLDPlugin.h中

    #import <Cordova/CDVPlugin.h>
    #import <Cordova/CDV.h>
    #import "MyApp-Swift.h"
    
    

    参考质料

    https://codepureandsimple.com/implementing-cordova-hot-code-push-in-your-ionic-app-247cda24d6d4

    1 条回复
    calciferAI 3个月前

    学习了

    关于 广告投放
    ©2016 - 2018 V4.1.6 Powered by 北京雏森科技有限公司