在webView中實現(xiàn)oc與js的交互一般有兩種方式:
1殿较、攔截點擊事件的URL進(jìn)行交互
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *path=[[request URL] absoluteString];
if ([path isEqualToString:[NSString stringWithFormat:@"%@/ddhong/user/bindMadaiAccountSuc.jsp",kBaseUrl]]) {
....進(jìn)行事件處理.......
}
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
NSString *path=[[request URL] absoluteString];
if ([path isEqualToString:[NSString stringWithFormat:@"%@/application/skiptoalllistcreditloan",kBaseUrl]]) {
.....進(jìn)行事件處理......
}
}
return YES;
}
2厉萝、用JavaScriptCore實現(xiàn)交互
導(dǎo)入頭文件:
#import<JavaScriptCore/JavaScriptCore.h
@protocol JSObjcDelegate <JSExport>
//這兩個方法的名字必須與js頁面里面調(diào)用的方法名字一致
- (void)jumpPublishDynamic;
- (void)jumpLogin;
@end
@interfaceViewController()
@property(nonatomic,strong)UIWebView*webView;
@property(nonatomic,strong)JSContext *jsContext;
@end
@implementation ViewController
- (void)viewDidLoad {??
???? [superviewDidLoad];? ?
???? [selfCustomUI];
}
- (void)CustomUI{
?? self.webView = [[UIWebViewalloc]initWithFrame:self.view.bounds];
self.webView.delegate =self;?
? [self.view addSubview:_webView];
NSURL*url = [[NSBundlemainBundle] URLForResource:@"untitled3"withExtension:@"html"];
? [self.webView loadRequest:[NSURLRequestrequestWithURL:url]];
}
- (void)webViewDidFinishLoad:(UIWebView*)webView{
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//此處的JSInterface必須與js頁面調(diào)用方面的類名名字一致
self.jsContext[@"JSInterface"] = self;
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"異常信息:%@", exceptionValue);
};
}
//js調(diào)用oc方法的實現(xiàn)
#pragma mark - JSObjcDelegate
- (void)jumpPublishDynamic {
[self pushController:[PublishViewController class] withTitle:@""];
}
- (void)jumpLogin {
[self pushController:[LoginViewController class] withInfo:nil];
}