在ios8中引入了WKWebView控件贪嫂,通過在頭文件引用#import <WebKit/WebKit.h>來使用該控件缓待,
這個控件與oc的原生控件uiwebview很相似渐裸,它更方便oc與js的相互通訊茎活。
1.oc調(diào)用js方法例子:
//通過方法:
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id,NSError *))completionHandler;
//調(diào)用js中的方法沸版,例如我們可以這樣使用這個方法:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSString *promptCode = [NSStringstringWithFormat:@"mymethd(\"%@\")",self.data];
[_theWebView evaluateJavaScript:promptCode completionHandler:^(id object,NSError *error) { }];
}
當wkwebview把html加載完之后,調(diào)用此方法楞件,其中@"mymethd("%@")"衫生,是方法名和要傳的參數(shù)
2.js給oc發(fā)送通知例子:
- (void)viewDidLoad {
NSString *path = [[NSBundlemainBundle]pathForResource:@"htmlname"ofType:@"html"];
NSURL *url = [NSURLfileURLWithPath:path];
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
WKWebViewConfiguration *theConfiguration =
[[WKWebViewConfigurationalloc]init];
[theConfiguration.userContentController
addScriptMessageHandler:selfname:@"myName"];
_theWebView = [[WKWebViewalloc]initWithFrame:self.view.frame
configuration:theConfiguration];
_theWebView.navigationDelegate =self;
//- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation方法代理
[_theWebViewloadRequest:request];
[self.viewaddSubview:_theWebView];
}
//在js方法中這樣給oc發(fā)送通知:
function postMyMessageA()
{
var message = {'message' :'You choose the A'};
window.webkit.messageHandlers.myName.postMessage(message);
}
//這是oc中收到通知后回調(diào)的方法:
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message
{
NSDictionary * messageDic = [[NSDictionaryalloc]initWithDictionary:message.body];
NSString * messageStr = [messageDicobjectForKey:@"message"];
UIAlertView * messAlert = [[UIAlertViewalloc]initWithTitle:nilmessage:messageStrdelegate:nilcancelButtonTitle:@"yes"otherButtonTitles:nil,nil];
[messAlertshow];
}