ionic热更新重开app内容不更新问题解决方案

更新ionic最新版之后,发现新ionic3项目的热更新会出现首次开启会更新内容,再次开启内容会变成更新前,而且不再触发热更新的问题。
cordova-hot-code-push已于2018-09-30停止更新,项目弃用。

经过调试代码和Google,发现是由于cordova-plugin-ionic-webview升级导致。

系统环境

Ionic:
   Ionic CLI          : 5.2.8
   Ionic Framework    : ionic-angular 3.9.5
   @ionic/app-scripts : 3.2.2
Cordova:
   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : android 8.0.0
System:
   Android SDK Tools : 26.1.1 
   NodeJS            : v10.16.3
   npm               : 6.9.0

解决方案

在热更新插件启动完毕和热更新文件下载完毕后重设localserver根目录,并重启localserver

安卓改动

改动redirectToLocalStorageIndexPage方法,使用java的反射机制

private void redirectToLocalStorageIndexPage() {
        final String indexPage = getStartingPage();

        // remove query and fragment parameters from the index page path
        // TODO: cleanup this fragment
        String strippedIndexPage = indexPage;
        if (strippedIndexPage.contains("#") || strippedIndexPage.contains("?")) {
            int idx = strippedIndexPage.lastIndexOf("?");
            if (idx >= 0) {
                strippedIndexPage = strippedIndexPage.substring(0, idx);
            } else {
                idx = strippedIndexPage.lastIndexOf("#");
                strippedIndexPage = strippedIndexPage.substring(0, idx);
            }
        }

        // make sure, that index page exists
        String external = Paths.get(fileStructure.getWwwFolder(), strippedIndexPage);
        if (!new File(external).exists()) {
            Log.d("CHCP", "External starting page not found. Aborting page change.");
            return;
        }
        try {
            Log.d("CHCP", "begin restart app");
            String basePath = fileStructure.getWwwFolder();
            // 尝试重置本地服务器根目录为当前热更新后的外置存储路径
            Class[] cArg = new Class[1];
            cArg[0] = String.class;
            // 此处重置loacalserver的根目录
            webView.getEngine().getClass().getDeclaredMethod("setServerBasePath", cArg).invoke(webView.getEngine(),
                    basePath);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();

        }

        Log.d("CHCP", "Loading external page: " + external);
    }

iOS改动

iOS的改动有两处,一处是热更新插件加载完毕后和热更新文件下载完成后都需要重定向localserver的根目录

为了与其他插件耦合,采用了objective-c

/**
 * 切换本地服务根目录到外存储目录
 */
-(void) switchServerBaseToExternalPath{
    
    NSString * basePath = [_filesStructure.wwwFolder.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@""];
    // 先要确保webVieEngine能响应以下两个方法
    if([self.webViewEngine respondsToSelector:@selector(setServerPath:)] && [self.webViewEngine respondsToSelector:@selector(basePath)]){
        // 先判断之前的本地服务根目录是否与将要切换的路径相同,如果不相同则切换,否则不切换
        NSString * preBasePath = [self.webViewEngine performSelector:@selector(basePath)];
        if( ![preBasePath isEqualToString:basePath] && [[NSFileManager defaultManager] fileExistsAtPath:basePath]){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                // 此处需要在主线程中调用,否则会出现意想不到的错误
                [self.webViewEngine performSelector:@selector(setServerPath:) withObject:basePath];
            });
            
        }
        NSLog(@"reset the base server success, start reload app");
    }else{
        // 如果不能响应,则不需要再调用切换了,保持APP在未更新状态
        NSLog(@"cannot reset the base server, keep current page");
    }
}

改动resetIndexPageToExternalStorage如下:

/**
 *  Redirect user to the index page that is located on the external storage.
 */
- (void)resetIndexPageToExternalStorage {
    NSString *indexPageStripped = [self indexPageFromConfigXml];
    
    NSRange r = [indexPageStripped rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"?#"] options:0];
    if (r.location != NSNotFound) {
        indexPageStripped = [indexPageStripped substringWithRange:NSMakeRange(0, r.location)];
    }
    
    NSURL *indexPageExternalURL = [self appendWwwFolderPathToPath:indexPageStripped];
    if (![[NSFileManager defaultManager] fileExistsAtPath:indexPageExternalURL.path]) {
        return;
    }
    
    // rewrite starting page www folder path: should load from external storage
    if ([self.viewController isKindOfClass:[CDVViewController class]]) {
        // 在此处重置localserver
        [self switchServerBaseToExternalPath];
    } else {
        NSLog(@"HotCodePushError: Can't make starting page to be from external storage. Main controller should be of type CDVViewController.");
    }
}

插件更新

在github上找到有大神修改的插件版本teh-hot-code-push-plugin,测试可用:

cordova plugin add teh-hot-code-push-plugin