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..postMessage()

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 
@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];
   
}

你可能感兴趣的:(iOS InAppBrowser 调用原生插件)