OC与JS交互 - JavaScriptCore

1. 首先引入JavaScriptCore库

OC与JS交互 - JavaScriptCore_第1张图片

使用的时候导入头文件#import

2. 本地一个html文件用做测试




    
    OC与JS交互
    


    
    

3. JavaScriptCore的OC与JS交互

// 加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // OC 调用 JS --> stringByEvaluatingJavaScriptFromString
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.navigationItem.title = title;
    NSLog(@"****************华丽的分界线****************");
    NSLog(@"加载完成咯!!!!");
    
    // JSContext就为其提供着运行环境 H5上下文
    JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // 保存全局变量
    self.jsContext = jsContext;
    
    // 异常处理
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        NSLog(@"context = %@", context);
        NSLog(@"exception = %@", exception);
    };
    
    // 提供全局变量
    [self.jsContext evaluateScript:@"var arr = ['apple', 'orange', 'banna'];"];
    
    // JS 调用 OC
    self.jsContext[@"ios_showMessage"] = ^() {
        NSLog(@"来了");
        NSArray *args = [JSContext currentArguments];
        NSLog(@"args = %@", args);
        
        //OC调用JS 传参
        NSDictionary *dict = @{@"name":@"spirej", @"age":@18};
        [[JSContext currentContext][@"ios_ocCalljs"] callWithArguments:@[dict, @"love"]];
    };
}

3.1 拿到H5上下文JSContext

// JSContext就为其提供着运行环境 H5上下文
JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

3.2 JS调用OC

// JS 调用 OC
self.jsContext[@"ios_showMessage"] = ^() {
    NSLog(@"来了");
    NSArray *args = [JSContext currentArguments];
    NSLog(@"args = %@", args);
};

ios_showMessage()是JS里定义的方法

3.3 OC调用JS

NSString *jsFunctStr = [NSString stringWithFormat:@"showAlert()"];
[self.jsContext evaluateScript:jsFunctStr];

ios_ocCalljs()是JS里定义的方法,OC调用并可传参

4. JS操作OC对象

4.1 声明一个SP_JSObject类

#import 
#import 

NS_ASSUME_NONNULL_BEGIN

@protocol SPProtocol 

- (void)doSomething;

- (void)doSomething2:(NSString *)str;

// 协议 - 协议方法
JSExportAs(getS, - (int)getSum:(int)num1 num2:(int)num2);

@end

@interface SP_JSObject : NSObject

@end

NS_ASSUME_NONNULL_END

自定义的协议方法

- (void)doSomething {
    NSLog(@"doSomething 来了");
}

- (void)doSomething2:(NSString *)str {
    NSLog(@"doSomething2 来了 -- %@", str);
}

- (int)getSum:(int)num1 num2:(int)num2 {
    NSLog(@"getSum 来了");
    // int (nil) - jsvalue (0)
    NSLog(@"num1 = %d, num2 = %d", num1, num2);
    return num1+num2;
}

JS里面有这样一个方法,分别调用了SP_JSObject对象的协议方法

function controlObject(){
    spObject.doSomething();
    spObject.doSomething2("艾欧尼亚");
    spObject.getS(10, 20);        
}

在OC端初始化SP_JSObject对象,并赋给JS端,JS端就可调起SP_JSObject的对象方法

// JS 操作对象
SP_JSObject *spObject = [[SP_JSObject alloc] init];
self.jsContext[@"spObject"] = spObject;

4. demo JS与OC交互,打开手机相册

4.1 JS端有一个打开相册的button和响应方法,还有一个显示图片的方法

function openAlbumImage(){
    getImage();
}

function showImage(imageDataStr){
    var tz_img = document.getElementById("tz_image");
    tz_img.innerHTML = "";
}


4.2 遵循协议,并声明相册控制器



@property (nonatomic,strong) UIImagePickerController *imagePicker;

4.3 JS交互OC,初始化相册控制器

// 打开相册
__weak typeof(self) weakSelf = self;
self.jsContext[@"getImage"] = ^() {
    
    weakSelf.imagePicker = [[UIImagePickerController alloc] init];
    weakSelf.imagePicker.delegate = weakSelf;
    weakSelf.imagePicker.allowsEditing = YES;
    weakSelf.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [weakSelf presentViewController:weakSelf.imagePicker animated:YES completion:nil];
};

4.4 实现协议方法,最后OC调JS传图片给JS显示

#pragma mark -- UIImagePickerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSLog(@"info---%@",info);
    UIImage *resultImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    NSData *imgData = UIImageJPEGRepresentation(resultImage, 0.01);
    NSString *encodedImageStr = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    [self removeSpaceAndNewline:encodedImageStr];
    [self dismissViewControllerAnimated:YES completion:nil];
    NSString *imageString = [self removeSpaceAndNewline:encodedImageStr];
    // 拿到图片后,调用JS方法,把图片传给JS显示
    NSString *jsFunctStr = [NSString stringWithFormat:@"showImage('%@')",imageString];
    [self.jsContext evaluateScript:jsFunctStr];
}

- (NSString *)removeSpaceAndNewline:(NSString *)str
{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}

文中所有示例demo可以在这里下载
https://github.com/SPIREJ/OCJS

你可能感兴趣的:(OC与JS交互 - JavaScriptCore)