iOS InAppBrowser 调用原生插件

需求:当前APP许多页面是由InAppBrowser打开的新的webview展示页面,但是同时需求需要调用原生的选图/看图插件等。

环境:InAppBrowser插件由原来的uiwebivew升级为wkwebiview,基于wkwebivew开发此功能。

步骤:

1.创建wkwebivew的时候,向js注入cordva方法

    WKUserContentController* userContentController = [[WKUserContentController alloc] init];
    WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = userContentController;
    configuration.processPool = [[CDVWKProcessPoolFactory sharedFactory] sharedProcessPool];
    
    [configuration.userContentController addScriptMessageHandler:self name:IAB_BRIDGE_NAME];
    [configuration.userContentController addScriptMessageHandler:self name:@"cordova"];

    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];

2.h5调用原生插件

// name填入cordova messageBody为插件的参数
// 原生解析的时候,只需拦截messageBody.name 等于cordova的消息
window.webkit.messageHandlers.<name>.postMessage(<messageBody>)

3.原生调用cordva插件

#pragma mark WKScriptMessageHandler delegate
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
 if ([message.name isEqualToString:@"cordova"]) {
      
      // 获取到根控制器MainViewContoller,因为这个控制器初始化了Cordova插件,需要用这个控制器来调用插件
      AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
      UIViewController *rootViewController = appdelegate.window.rootViewController;
      CDVViewController *vc = (CDVViewController *) rootViewController;

      // 解析调用插件所需要的参数
      NSArray *jsonEntry = message.body;
      CDVInvokedUrlCommand* command = [CDVInvokedUrlCommand commandFromJson:jsonEntry];

       // 用根控制器上的commandQueue方法,调用插件
      if (![vc.commandQueue execute:command]) {
#ifdef DEBUG
          NSError* error = nil;
          NSString* commandJson = nil;
          NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonEntry
                                                             options:0
                                                               error:&error];

          if (error == nil) {
              commandJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
          }

          static NSUInteger maxLogLength = 1024;
          NSString* commandString = ([commandJson length] > maxLogLength) ?
          [NSString stringWithFormat : @"%@[...]", [commandJson substringToIndex:maxLogLength]] :
          commandJson;

          NSLog(@"FAILED pluginJSON = %@", commandString);
#endif
      }
  }
}

#pragma mark WKScriptMessageHandler delegate
// didReceiveScriptMessage代理方法接受到消息后,此方方法会接受到回调,也需处理
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
  if ([message.name isEqualToString:@"cordova"]) {
      return;
  }
}

这里存在一个问题,我们是通过根控制器调用的插件,如果需要present一个新的控制器显示,这时候是显示在根控制器上,但是在InAppBrowser之下,这里还需要处理一次,重写present方法,获取当前最上层控制器进行present。


#import "UIViewController+Present.h"
#import <objc/runtime.h>
@implementation UIViewController (Present)

+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method presentM = class_getInstanceMethod(self.class, @selector(presentViewController:animated:completion:));
        Method presentSwizzlingM = class_getInstanceMethod(self.class, @selector(dy_presentViewController:animated:completion:));
        
        method_exchangeImplementations(presentM, presentSwizzlingM);
    });
}

- (void)dy_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {

    UIViewController *currentVc = [self topViewController];
    if ([currentVc  isKindOfClass:[UIAlertController class]]) {
        [self dy_presentViewController:viewControllerToPresent animated:flag completion:completion];
    } else {
        [[self topViewController] dy_presentViewController:viewControllerToPresent animated:flag completion:completion];
    }
    
}
- (UIViewController *)topViewController {
    
        UIViewController *topVC;
    
        topVC = [self getTopViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    
        while (topVC.presentedViewController) {
        
                topVC = [self getTopViewController:topVC.presentedViewController];
        
            }
    
        return topVC;
    
}
- (UIViewController *)getTopViewController:(UIViewController *)vc {
    
       if (![vc isKindOfClass:[UIViewController class]]) {
        
                return nil;
        
            }    if ([vc isKindOfClass:[UINavigationController class]]) {
            
                    return [self getTopViewController:[(UINavigationController *)vc topViewController]];
            
                } else if ([vc isKindOfClass:[UITabBarController class]]) {
                
                        return [self getTopViewController:[(UITabBarController *)vc selectedViewController]];
                
                    } else {
                    
                            return vc;
                    
                        }
    
}
@end

4.插件回传callback给h5

4.1修改原生本地corodva.js文件
由于原生是调用根控制器上的插件返回callback,是和InAppBrowser不同层级的webview,所以需要做一层转发,判断当前webview的callback数组,是否含有接收到的callbackid,如果不在在数组中,则说明不是该webview调用的插件,则调用InAppBrowser里的js回传方法,回传开InAppBrowser的webview接收callback

callbackFromNative: function(callbackId, isSuccess, status, args, keepCallback) {
        try {
            var callback = cordova.callbacks[callbackId];
            if (callback) {
                if (isSuccess && status == cordova.callbackStatus.OK) {
                    callback.success && callback.success.apply(null, args);
                } else if (!isSuccess) {
                    callback.fail && callback.fail.apply(null, args);
                }
                /*
                else
                    Note, this case is intentionally not caught.
                    this can happen if isSuccess is true, but callbackStatus is NO_RESULT
                    which is used to remove a callback from the list without calling the callbacks
                    typically keepCallback is false in this case
                */
                // Clear callback if not expecting any more results
                if (!keepCallback) {
                    delete cordova.callbacks[callbackId];
                }
       } else {
         // __globalBrowser为表示当前界面开启了InAppBrowser
         if(window.__globalBrowser) {
            var message = 'cordova.callbackFromNative("'+callbackId+'",'+isSuccess+',' + status +',' +JSON.stringify(args) + ',' + keepCallback + ')';
           // 调用InAppBrowser插件里的js回传方法
            window.__globalBrowser.executeScript({code: message});
         }
       }

4.2 修改inappbrowser.js

 module.exports = function(strUrl, strWindowName, strWindowFeatures, callbacks) {
        // Don't catch calls that write to existing frames (e.g. named iframes).
        if (window.frames && window.frames[strWindowName]) {
            var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
            return origOpenFunc.apply(window, arguments);
        }

        strUrl = urlutil.makeAbsolute(strUrl);
        var iab = new InAppBrowser();

        callbacks = callbacks || {};
        for (var callbackName in callbacks) {
            iab.addEventListener(callbackName, callbacks[callbackName]);
        }

        var cb = function(eventname) {
           iab._eventHandler(eventname);
        };

        strWindowFeatures = strWindowFeatures || "";
    
        exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
        // 声明全局变量__globalBrowser,表示当前界面开启了InAppBrowser
        window.__globalBrowser = iab;
        return iab;

5.如果调用了选择图片插件,h5回显本地图片需要原生拦截scheme请求

5.1 创建wkwebivew,注入js方法,用于h5调用插件

 WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = userContentController;
    configuration.processPool = [[CDVWKProcessPoolFactory sharedFactory] sharedProcessPool];
    
    [configuration.userContentController addScriptMessageHandler:self name:IAB_BRIDGE_NAME];
    // 注册cordova方法,让h5调用
    [configuration.userContentController addScriptMessageHandler:self name:@"cordova"];

    //self.webView = [[WKWebView alloc] initWithFrame:frame];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];

5.2 回传参数内需要写入自定义scheme协议

// 是否是InAppBrowser调用的插件
// ExeInAppBrowserShow 这个值需要在InAppBrowser开启和关闭的时候赋值
BOOL isInappBro =  [[[NSUserDefaults standardUserDefaults] objectForKey:ExeInAppBrowserShow] boolValue];
if (isInappBro) {
  [resultStrings addObject:[url.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@"miexe.com://"]];
else {
  [resultStrings addObject:url.absoluteString];
}
[self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:resultStrings] callbackId:self.callbackId];

5.3 在MyCustomURLProtocol类中,需要实现三个方法:

// 每次有一个请求的时候都会调用这个方法,在这个方法里面判断这个请求是否需要被处理拦截,如果返回YES就代表这个request需要被处理,反之就是不需要被处理。
+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest{
   if ([theRequest.URL.scheme caseInsensitiveCompare:@"miexe.com"] == NSOrderedSame) {
       return YES;
   }
   return NO;
}

// 这个方法就是返回规范的request,一般使用就是直接返回request,不做任何处理的    
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)theRequest{
   return theRequest;
}

// 这个方法作用很大,把当前请求的request拦截下来以后,在这个方法里面对这个request做各种处理,比如添加请求头,重定向网络,使用自定义的缓存等。
// 我们在这里将自定义协议的scheme去除掉。然后返回file协议给h5
- (void)startLoading{
   NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[self.request URL]
                                                       MIMEType:@"image/png"
                                          expectedContentLength:-1
                                               textEncodingName:nil];
   NSString *imagePath = [self.request.URL.absoluteString componentsSeparatedByString:@"miexe.com://"].lastObject;
   NSData *data = [NSData dataWithContentsOfFile:imagePath];
   [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
   [[self client] URLProtocol:self didLoadData:data];
   [[self client] URLProtocolDidFinishLoading:self];
   
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,188评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,464评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,562评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,893评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,917评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,708评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,430评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,342评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,801评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,976评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,115评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,804评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,458评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,008评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,135评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,365评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,055评论 2 355

推荐阅读更多精彩内容