In Wkwebview and JavaScript interactions, the method of injecting MessageHandler into the messagehandler,app is often injected into the native
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; config.userContentController = [WKUserContentController new]; //注入handler [config.userContentController addScriptMessageHandler:self name:@"HandlerName"];
Here we find a strong reference to self when injecting handler into JS, resulting in a memory leak
Workaround add a new class Weakscriptmessagedelegate
@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;@end@implementation WeakScriptMessageDelegate- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate { self = [super init]; if (self) { _scriptDelegate = scriptDelegate; } return self;}- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];}@end
With the following line of code added, Viewcontroller calls the Dealloc method, at which point Viewcontroller is released normally. But Weakscriptmessagedelegate is not released and needs to be released in Dealloc Weakscriptmessagedelegate.
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; config.userContentController = [WKUserContentController new]; //注入handler [config.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"HandlerName"];
Release Weakscriptmessagedelegate implemented in the Dealloc method
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"HandlerName"];
IOS add Wkwebview causes the controller to not release the issue