当前位置 博文首页 > dengren1956的博客:iOS 混合开发之 Cordova 实践

    dengren1956的博客:iOS 混合开发之 Cordova 实践

    作者:[db:作者] 时间:2021-09-20 16:34

      在15年时,之前公司使用 Cordova 做混合开发使用,后来公司没有用到了,现在重新记录下。

    ?  Cordova (官网:http://cordova.apache.org/)简介:

      Apache Cordova 是一个开源移动开发框架,可以使用标准的Web 技术 HTML5、CSS3、JavaScript用来开发跨平台的移动应用。架构图如下(来源官网):

      

      大致分为 Web 端的工作原理和 Native 端的工作原理。

      Web 端,主目录下有 Config.xml 和 www 文件夹。Config.xml 文件包含了 APP 配置信息:App 名称、入口index文件、插件、白名单、WebView 初始化的配置信息、Icon 图标等。

      Native 端有 CDVViewController、CDVUIWebViewEngine。

      其中,CDVViewController 中:

      init 初始化程序;

      loadSettings 解析Config.xml 文件,将 pluginsMap startPlugin setting startpage 变量初始到容器 controller 中初始化 plugin 字典;

      ViewDidLoad 先loadSettings,之后创建特殊存储空,根据CDVUIWebViewEngine初始化Webview,然后获取appURL加载index.html。

      在 CDVUIWebViewNavigationDelegate中,- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType?

      是 JS 通知 Native 所有入口,所有 JS 调用 Native 都需要经过这个重新实现了 UIWebView 中 UIWebViewDelegate 协议中 shouldStartLoadWithRequest ,对于所有请求做个拦截,对于 URL 中带 Gap 的都会执行 CDVViewController 中的 CommandQueue
    - (void)fetchCommandsFromJs
    {
        __weak CDVCommandQueue* weakSelf = self;
        NSString* js = @"cordova.require('cordova/exec').nativeFetchMessages()";
    
        [_viewController.webViewEngine evaluateJavaScript:js
                                        completionHandler:^(id obj, NSError* error) {
            if ((error == nil) && [obj isKindOfClass:[NSString class]]) {
                NSString* queuedCommandsJSON = (NSString*)obj;
                CDV_EXEC_LOG(@"Exec: Flushed JS->native queue (hadCommands=%d).", [queuedCommandsJSON length] > 0);
                [weakSelf enqueueCommandBatch:queuedCommandsJSON];
                // this has to be called here now, because fetchCommandsFromJs is now async (previously: synchronous)
                [self executePending];
            }
        }];
    }
    cs