美文网首页
javascript与oc的互相调用

javascript与oc的互相调用

作者: 狒狒James_Leo | 来源:发表于2017-09-14 11:03 被阅读0次
//html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;" />
    <title>JavaScriptCore</title>
</head>
<body>
    <div style="width:300px; margin: 0 auto;background:red;">
        <input type="button" value="带两个参数的方法" onclick="Native.testMethodWithParam1Param2('param1_value', 'param2_value')" />
        <br />
        <input type="button" value="带两个参数的方法2" onclick="Native.testMethod(1111, '2222')" />
        <br /> 
        <input type="button" value="带一个参数的方法" onclick="Native.testLog('带一个参数')" />
        <br />
        <input type="button" value="参数为数组的方式" onclick="Native.testArray([1111, '2222'])" />
        <br />
        <input type="button" value="测试log" onclick="log('测试')" />
        <br />
        <input type="button" value="JS调用OC原生提示框" onclick="alert('alert')" />
        <br />
        <input type="button" value="添加视图" onclick="addSubView('view')" />
        <br />
        <div>
            <span>输入一个整数:</span>
            <input id="input" type="text" />
            <br />
            结果为:<p id="result"></p>
        </div>
        <input type="button" value="计算阶乘" onclick="Native.calculateForJS(input.value)" />
    </div>
</body>
<script type="text/javascript">
    function showResult(resultNumber) {
        document.getElementById("result").innerText = resultNumber;
    }
</script>
</html>



//oc中的代码 .h文件中
#import <UIKit/UIKit.h>
#import <JavaScriptCore/JavaScriptCore.h>

//主要是声明协议继承自JSEXport协议
@protocol JSOCExport <JSExport>

/** 带两个参数的方法 */
- (void)testMethodWithParam1:(NSString *)param1 Param2:(NSString *)param2;
/** 带两个参数的方法(2) */
- (void)test:(NSNumber *)param1 method:(NSString *)param2;
/** 带一个参数的方法 */
- (void)testLog:(NSString  *)logText;
/** 参数以数组的方式 */
- (void)testArray:(NSArray *)dataArray;
- (void)calculateForJS:(NSNumber *)number;

@end

@interface SQViewController : UIViewController

@end


//.m文件
#import "SQViewController.h"

@interface SQViewController ()<UIWebViewDelegate, JSOCExport>
{
    UIWebView *myWebView;
    JSContext *context;
}
@end

@implementation SQViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"info.html"];
    myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
    myWebView.delegate = self;
    NSURL *URL = [NSURL URLWithString:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    [myWebView loadRequest:request];
    [self.view addSubview:myWebView];
}

#pragma mark -- UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // 设置导航栏title
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    // 设置页面元素
//    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.display = 'none'"];
    context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // 打印异常
    context.exceptionHandler = ^(JSContext *context, JSValue *exceptions) {
        context.exception = exceptions;
        NSLog(@"%@", exceptions);
    };
    
    // 以 JSExport 协议    关联 Native
    context[@"Native"] = self;
    
    // 以block 形式关联 JS中的func
    context[@"log"] = ^(NSString *str) {
        NSLog(@"log = %@", str);
    };
    
    __weak  UIViewController *vc = self;
    context[@"ale"] = ^(NSString *str) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"msg from js" message:str preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:action];
            [vc presentViewController:alert animated:YES completion:nil];
        });
    };
    
    context[@"addSubView"] = ^{

    //这句话是错误的  应该放在主线程中进行
        UIView *v = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
        v.backgroundColor = [UIColor redColor];
        [v addSubview:[[UISwitch alloc] init]];
        [vc.view addSubview:v];
    };
    
//    [context[@"showResult"] callWithArguments:@[@4]];
}

- (void)calculateForJS:(NSNumber *)number {
    int sum = 1;
    for (int i = 1; i <= [number intValue]; i++) {
        sum *= i;
    }
    NSString *str = [NSString stringWithFormat:@"showResult('%d')", sum];
//    [myWebView stringByEvaluatingJavaScriptFromString:str];
    [context evaluateScript:str];
}

/** 带两个参数的方法 */
- (void)testMethodWithParam1:(NSString *)param1 Param2:(NSString *)param2 {
    NSLog(@"testMethodWithParam1 = %@, param2 = %@", param1, param2);
}
/** 带两个参数的方法(2) */
- (void)test:(NSNumber *)param1 method:(NSString *)param2 {
    NSLog(@"testParams = %@, method = %@", param1, param2);
}
/** 带一个参数的方法 */
- (void)testLog:(NSString *)logText {
    NSLog(@"testLog = %@", logText);
}
/** 参数以数组的方式 */
- (void)testArray:(NSArray *)dataArray {
    NSLog(@"testArray = %@", dataArray);
}
                 
                 
                 
                 
                 
                 
                 
                 
                 
                 
@end













相关文章

网友评论

      本文标题:javascript与oc的互相调用

      本文链接:https://www.haomeiwen.com/subject/cfufyttx.html