From 4f4644ffd836253f1f91cebf215f768932746dfb Mon Sep 17 00:00:00 2001 From: sunzhongliang <543167061@qq.com> Date: Fri, 27 Dec 2019 18:39:53 +0800 Subject: [PATCH] fix(iOS): WKWebView RetainCycle (#1096) --- ios/RNCWebView.h | 5 +++++ ios/RNCWebView.m | 23 +++++++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/ios/RNCWebView.h b/ios/RNCWebView.h index ed67b4c..7cac927 100644 --- a/ios/RNCWebView.h +++ b/ios/RNCWebView.h @@ -19,6 +19,11 @@ @end +@interface RNCWeakScriptMessageDelegate : NSObject +@property (nonatomic, weak) id scriptDelegate; +- (instancetype)initWithDelegate:(id)scriptDelegate; +@end + @interface RNCWebView : RCTView @property (nonatomic, weak) id _Nullable delegate; diff --git a/ios/RNCWebView.m b/ios/RNCWebView.m index a5c77db..5e17593 100644 --- a/ios/RNCWebView.m +++ b/ios/RNCWebView.m @@ -162,7 +162,8 @@ static NSDictionary* customCertificatesForHost; wkWebViewConfig.userContentController = [WKUserContentController new]; // Shim the HTML5 history API: - [wkWebViewConfig.userContentController addScriptMessageHandler:self name:HistoryShimName]; + [wkWebViewConfig.userContentController addScriptMessageHandler:[[RNCWeakScriptMessageDelegate alloc] initWithDelegate:self] + name:HistoryShimName]; NSString *source = [NSString stringWithFormat: @"(function(history) {\n" " function notify(type) {\n" @@ -187,7 +188,8 @@ static NSDictionary* customCertificatesForHost; [wkWebViewConfig.userContentController addUserScript:script]; if (_messagingEnabled) { - [wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName]; + [wkWebViewConfig.userContentController addScriptMessageHandler:[[RNCWeakScriptMessageDelegate alloc] initWithDelegate:self] + name:MessageHandlerName]; NSString *source = [NSString stringWithFormat: @"window.%@ = {" @@ -1077,3 +1079,20 @@ static NSDictionary* customCertificatesForHost; } @end + +@implementation RNCWeakScriptMessageDelegate + +- (instancetype)initWithDelegate:(id)scriptDelegate { + self = [super init]; + if (self) { + _scriptDelegate = scriptDelegate; + } + return self; +} + +- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { + [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message]; +} + +@end +