Cordova之JS与iOS通信

目前项目中使用到Cordova,原生与h5混合开发。实际上项目中很多页面都是由h5完成的,但不知为啥,h5大概是不喜欢用Cordova,原生写的很多插件他们并没有调用。h5需要与原生交互时,就叫我加方法,加的方法名字放在一个方法数组里,用NSTimer每隔0.1s用UIWebView的stringByEvaluatingJavaScriptFromString方法调用h5写的公共方法得到一个方法id,for循环方法数组,如果在数组中找到了该方法id对应的方法就调用之。这种方式效率低,我自己看着也是浑身鸡皮疙瘩。在我的坚持下,h5在慢慢改为调用Cordova插件。

JS与iOS通信方式

  1. 通过设置透明的iframe的src属性;
  2. 使用XMLHttpRequest发起请求。

一.设置透明的iframe的src属性

  1. cordova.exec函数里通过向html插入一个不可见的iframe,设置这个iframe的src为自定义的协议;在"cordova.js"文件中
    
    function pokeNative() {
    // CB-5488 - Don't attempt to create iframe before document.body is available.
    if (!document.body) {
        setTimeout(pokeNative);
        return;
    }
    
    // Check if they've removed it from the DOM, and put it back if so.
    if (execIframe && execIframe.contentWindow) {
        execIframe.contentWindow.location = 'gap://ready';
    } else {
        execIframe = document.createElement('iframe');
        execIframe.style.display = 'none';
        execIframe.src = 'gap://ready';
        document.body.appendChild(execIframe);
    }
    
    failSafeTimerId = setTimeout(function() {
        if (commandQueue.length) {
            // CB-10106 - flush the queue on bridge change
            if (!handleBridgeChange()) {
                pokeNative();
             }
        }
    }, 50); 
}
  1. 而iframe的src更改时,UIWebView会触发回调- (BOOL)webView:(UIWebView)theWebView shouldStartLoadWithRequest:(NSURLRequest)request navigationType:(UIWebViewNavigationType)navigationType。
    判断是否是Cordova请求,对url的协议是gap时,获取请求的参数然后分发到plugin的方法里去。
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL* url = [request URL];
    CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;
     
     //看这里看这里
    if ([[url scheme] isEqualToString:@"gap"]) {
        [vc.commandQueue fetchCommandsFromJs];
        // The delegate is called asynchronously in this case, so we don't have to use
        // flushCommandQueueWithDelayedJs (setTimeout(0)) as we do with hash changes.
        [vc.commandQueue executePending];
        return NO;
    }

    //此处删除了非关键代码
    
    return NO;
}
  1. fetchCommandsFromJS:OC调用JS的cordova.require('cordova/exec').nativeFetchMessages()函数获取一个json字符串,该json字符串包含:要调用的插件名字、方法名、参数、回调id。
- (void)fetchCommandsFromJs
{
    // Grab all the queued commands from the JS side.
    NSString* queuedCommandsJSON = [_viewController.webView
                                      stringByEvaluatingJavaScriptFromString:
                                          @"cordova.require('cordova/exec').nativeFetchMessages()"];

    [self enqueCommandBatch:queuedCommandsJSON];
    if ([queuedCommandsJSON length] > 0) {
        CDV_EXEC_LOG(@"Exec: Retrieved new exec messages by request.");
    }
}
  1. 具体分发是在函数- (BOOL)execute:(CDVInvokedUrlCommand*)command里
    NSString* methodName = [NSString stringWithFormat:@"%@:", command.methodName];
    SEL normalSelector = NSSelectorFromString(methodName);
    if ([obj respondsToSelector:normalSelector]) {
        // [obj performSelector:normalSelector withObject:command];
        ((void (*)(id, SEL, id))objc_msgSend)(obj, normalSelector, command);
    } else {
        // There's no method to call, so throw an error.
        NSLog(@"ERROR: Method '%@' not defined in Plugin '%@'", methodName, command.className);
        retVal = NO;
    }

二、OC将请求的结果发给JS端

OC调用JS函数

NSString* js = [NSString stringWithFormat:@"cordova.require('cordova/exec').nativeCallback('%@',%d,%@,%d, %d)", callbackId, status, argumentsAsJSON, keepCallback, debug];

js = [NSString stringWithFormat:@"try{cordova.require('cordova/exec').nativeEvalAndFetch(function(){%@})}catch(e){console.log('exception nativeEvalAndFetch : '+e);};", js];

UIWebView调用stringByEvaluatingJavaScriptFromString执行上面的js,将请求状态,参数回传给JS

三、JS调用插件

// successCallback : 成功回调方法
// failCallback    : 失败回调方法
// server          : 所要请求的服务名字
// action          : 所要请求的服务具体操作
// actionArgs      : 请求操作所带的参数
cordova.exec(successCallback, failCallback, service, action, actionArgs);
  1. CordovaJS端为每个请求生成一个唯一标识callbackId,callbackId会传给OC端,OC端处理完后将callbacId连通处理结果一起返回给JS端;
  2. 以callbackId为key,{success:successCallback,fail:failCallback}为value,保存在JS端的callbacks字典里,successCallback和failCallback不会传给OC端,JS端根据OC端返回结果中带上的callbackId找到回调方法;
    if (successCallback || failCallback) {
        callbackId = service + cordova.callbackId++;
        cordova.callbacks[callbackId] =
            {success:successCallback, fail:failCallback};
    }
  1. 每次JS请求,最后发到OC的数据[callbackId, service, action, actionArgs];
    var command = [callbackId, service, action, actionArgs];

    // Stringify and queue the command. We stringify to command now to
    // effectively clone the command arguments in case they are mutated before
    // the command is executed.
    commandQueue.push(JSON.stringify(command));

OC拿到[callbackId, service, action, actionArgs]后的处理

  1. 根据service找到对应的插件;service是原生端配置在config.xml中feature节点的name值。
    
   
   
service为Camera,插件文件名是CDVCamera
  1. 根据action找到插件中对应的方法,并把actionArgs作为方法的参数传给方法;
  2. 处理完后,把callbackId和处理结果返回给JS,JS收到后根据callbackId找到回调方法,把处理结果传给回调方法。

二.XMLHttpRequest

  1. JS使用XMLHttpRequest发起一个请求execXhr.open('HEAD', "/!gap_exec?"+(+new Date()),true);

  2. 请求的地址是/!gap_exec;把请求的数据放在请求的header里面,execXhr.setRequestHeader('cmds', iOSExec.nativeFetchMessages());

  3. 而在 Objective-C 端使用一个 NSURLProtocol 的子类来检查每个请求,如果地址是 /!gap_exec 的话,则认为是 Cordova 通信的请求,直接拦截,拦截后就可以通过分析请求的数据,分发到不同的插件方法中。

这种方式我在最新的Cordova实现文件中没有找到。

你可能感兴趣的:(Cordova之JS与iOS通信)