addScriptMessageHandler很容易導(dǎo)致循環(huán)引用,控制器強(qiáng)引用了WKWebView,WKWebView copy(強(qiáng)引用了)configuration实幕,configuration copy(強(qiáng)引用了)userContentController
- 1.初始化WKWebView
- (void)initWKWebView {
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
preferences.minimumFontSize = 40.0;
configuration.preferences = preferences;
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
// 注冊
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"getLocation"];
}
- 2.WKScriptMessageHandler注冊Native方法
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"getLocation"]) {
[self getLocation];
}
}
#pragma mark - private method
- (void)getLocation {
// 獲取位置信息
···
// 將結(jié)果返回給js
NSString *locationStr = [NSString stringWithFormat:@"setLocation('%@')",@"廣東省深圳市南山區(qū)學(xué)府路XXXX號"];
[self.webView evaluateJavaScript:locationStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
- JS調(diào)用OC
function locationClick() {
window.webkit.messageHandlers.getLocation.postMessage(null);
}