H5 page calls native page, preferably JavaScriptCore, JSContext with JSExport:
- (void)setupJsContent {// Get the current JS context JSContext *_content = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; ExceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {context.exception = exceptionValue; NSLog(@"exceptionValue is %@", exceptionValue); }; YongLian *yonglian = [[YongLian alloc] init]; _content[@"YongLian"] = yonglian; yonglian.jsContext = _content; }Copy the code
Where the.h file of the class YongLian:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
NS_ASSUME_NONNULL_BEGIN
@protocol JavaScriptCoreOCDelegate <JSExport>
-(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<JavaScriptCoreOCDelegate>
@property (nonatomic, weak) JSContext *jsContext;
//@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, copy) YongLianImageClickBlock imageClickBlock;
@end
NS_ASSUME_NONNULL_END
Copy the code
.m files:
- (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];
}
});
}
Copy the code
In particular, when we have two arguments in JS, such as the -(void)onImage (NSNumber*)index clicked (NSString*)urls method, it looks like this:
YongLian.onImageClicked(index,urls);
Copy the code
The OC method name needs to be onImage:Clicked, which is exactly the same as the JS method name after the colon is removed.