iOS关于H5和原生页面交互

H5页面调用原生页面,首选JavaScriptCore,JSContext搭配JSExport:

- (void)setupJsContent
{
    //获取当前JS环境
    JSContext *_content = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // 打印异常
    _content.exceptionHandler =
    ^(JSContext *context, JSValue *exceptionValue)
    {
        context.exception = exceptionValue;
        NSLog(@"exceptionValue is %@", exceptionValue);
    };
    YongLian *yonglian = [[YongLian alloc] init];
    _content[@"YongLian"] = yonglian;
    yonglian.jsContext = _content;
}
复制代码

其中YongLian这个类的.h文件:

#import 
#import 
#import 
NS_ASSUME_NONNULL_BEGIN
@protocol JavaScriptCoreOCDelegate 

-(void)user_login:(NSString *)user_login;
-(void)chat_list:(NSString *)chat_list;
-(void)chat_user:(NSString *)chat_user;
-(void)onImage:(NSNumber*)index clicked:(NSString*)urls;
@end
typedef void(^YongLianImageClickBlock)(NSNumber*,NSArray*);
@interface YongLian : NSObject
@property (nonatomic, weak) JSContext *jsContext;
//@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, copy) YongLianImageClickBlock imageClickBlock;
@end

NS_ASSUME_NONNULL_END
复制代码

.m文件:

- (void)user_login:(NSString *)user_login{
    NSLog(@"user login");
    dispatch_async(dispatch_get_main_queue(), ^{
        UserInfoSingleton *userInfo = [UserInfoSingleton defaultUserInfo];
        LoginViewController_1 *loginVC = [LoginViewController_1 new];
        UINavigationController *nav4 = [[WKNavigationController alloc]initWithRootViewController:loginVC];
        if (!userInfo.login) {
            [[WKVCTools getCurrentVC].navigationController presentViewController:nav4 animated:true completion:nil];
        }
    });
    
}
复制代码

尤其需要注意的是,当我们在JS中是两个参数的时候,例如这里的-(void)onImage:(NSNumber*)index clicked:(NSString*)urls方法,在JS中是这样的:

YongLian.onImageClicked(index,urls);
复制代码

这个时候OC中的方法名字,就需要是onImage:Clicked也就是冒号去掉之后和JS方法名完全一致才行。

你可能感兴趣的:(移动开发)