我們?cè)谑褂肳KWebView的時(shí)候,需要與h5那邊進(jìn)行交互哩至,比如:h5那邊有個(gè)按鈕點(diǎn)擊躏嚎,iOS端需要監(jiān)聽(tīng)這個(gè)方法并作出相應(yīng)的邏輯處理,這時(shí)候我們就需要通過(guò)注冊(cè)方法來(lái)進(jìn)行交互菩貌,如下
[self.userContentController addScriptMessageHandler:self name:MethodName];
但我們退出該控制器的時(shí)候卢佣,就會(huì)發(fā)現(xiàn)dealloc
方法根本不會(huì)調(diào)用,導(dǎo)致內(nèi)存得不到釋放箭阶,這時(shí)候我們就要通過(guò)中間變量LAWKDelegateController
來(lái)注冊(cè)方法虚茶,解決內(nèi)存釋放問(wèn)題
- (void)viewDidLoad {
[super viewDidLoad];
//配置環(huán)境
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];
self.userContentController = [[WKUserContentController alloc]init];
configuration.userContentController = self.userContentController;
self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, 100, 100) configuration:configuration];
// self.webView.UIDelegate = self;
// self.webView.navigationDelegate = self;
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
[self.view addSubview:self.webView];
/**
注冊(cè)方法
addScriptMessageHandler:self
當(dāng)我們通過(guò)self注冊(cè)方法的時(shí)候,發(fā)現(xiàn)dealloc不會(huì)調(diào)用仇参,內(nèi)存得不到釋放
解決方法:
通過(guò)中間變量解決內(nèi)存釋放問(wèn)題:LAWKDelegateController
*/
// [self.userContentController addScriptMessageHandler:self name:MethodName];
LAWKDelegateController *delegateController = [[LAWKDelegateController alloc]init];
delegateController.delegate = self;
[self.userContentController addScriptMessageHandler:delegateController name:MethodName];
}
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol WKDelegate <NSObject>
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
@end
@interface LAWKDelegateController : UIViewController <WKScriptMessageHandler>
@property (weak , nonatomic) id<WKDelegate> delegate;
@end
NS_ASSUME_NONNULL_END
#import "LAWKDelegateController.h"
@interface LAWKDelegateController ()
@end
@implementation LAWKDelegateController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
if ([self.delegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
[self.delegate userContentController:userContentController didReceiveScriptMessage:message];
}
}
@end