iOS原生与JS互调

1,178 阅读1分钟

UIWebView下的JS互调

1.js调用原生

将原生对象注入到js

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    jsSDK *jssdk = [jsSDK new];
    jssdk.delegate = self;
    context[@"jsSDK"] = jssdk;
}

注入的 jsSDK 需要遵守 JSExport 协议

jsSDK的代理里面实现需要的具体方法

@protocol jsSDKDelegate <JSExport>

- (void)previewImages:(NSString *)url position:(int)position;
- (void)previewImages;

@end

@interface jsSDK : NSObject <jsSDKDelegate>

@property(nonatomic,weak) id<jsSDKDelegate> delegate;

@end
- (void)previewImages
{
    // 多参数解析  和前端开发约定好 不同数量的参数 需要调用原生不同的方法
    
    id args = [JSContext currentArguments];
    NSArray *argArr = args;
    
    // 这里约定必须有两个以上参数 所以有这个判断 根据实际情况修改 核心代码是解析出传递的参数
    
    if (argArr.count < 2) {
        return;
    }
    JSValue *url = argArr[0];
    NSString *urlStr = [url toString];
    
    JSValue *positionJSValue = argArr[1];
    int position = [[positionJSValue toString] intValue];
    
    [self.delegate previewImages:urlStr position:position];
}

原生调用js

xxJS 为前端一个全局持有的类 供原生调用 与上面 jsSDK 一样的作用。

- (void)loginSuccess
{
    JSContext *context=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // 无参数
    NSString *callBackJS = @"xxJS.loginSuccess";
    // 有参数
    NSString *callBackJS = @"xxJS.loginSuccess('参数')";
    
    [context evaluateScript:callBackJS];
}

wkwebview下的JS互调

没有实践过 参考参考其他文章吧

www.jianshu.com/p/ca7eb797c…

www.jianshu.com/p/9b4f7f6d4…