Skip to content

Commit 4f4644f

Browse files
sunzhongliangdeTitozzz
authored andcommitted
fix(iOS): WKWebView RetainCycle (react-native-webview#1096)
1 parent 7ba1bc5 commit 4f4644f

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

ios/RNCWebView.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@
1919

2020
@end
2121

22+
@interface RNCWeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>
23+
@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;
24+
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;
25+
@end
26+
2227
@interface RNCWebView : RCTView
2328

2429
@property (nonatomic, weak) id<RNCWebViewDelegate> _Nullable delegate;

ios/RNCWebView.m

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,8 @@ - (void)didMoveToWindow
162162
wkWebViewConfig.userContentController = [WKUserContentController new];
163163

164164
// Shim the HTML5 history API:
165-
[wkWebViewConfig.userContentController addScriptMessageHandler:self name:HistoryShimName];
165+
[wkWebViewConfig.userContentController addScriptMessageHandler:[[RNCWeakScriptMessageDelegate alloc] initWithDelegate:self]
166+
name:HistoryShimName];
166167
NSString *source = [NSString stringWithFormat:
167168
@"(function(history) {\n"
168169
" function notify(type) {\n"
@@ -187,7 +188,8 @@ - (void)didMoveToWindow
187188
[wkWebViewConfig.userContentController addUserScript:script];
188189

189190
if (_messagingEnabled) {
190-
[wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
191+
[wkWebViewConfig.userContentController addScriptMessageHandler:[[RNCWeakScriptMessageDelegate alloc] initWithDelegate:self]
192+
name:MessageHandlerName];
191193

192194
NSString *source = [NSString stringWithFormat:
193195
@"window.%@ = {"
@@ -1077,3 +1079,20 @@ - (NSURLRequest *)requestForSource:(id)json {
10771079
}
10781080

10791081
@end
1082+
1083+
@implementation RNCWeakScriptMessageDelegate
1084+
1085+
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
1086+
self = [super init];
1087+
if (self) {
1088+
_scriptDelegate = scriptDelegate;
1089+
}
1090+
return self;
1091+
}
1092+
1093+
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
1094+
[self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
1095+
}
1096+
1097+
@end
1098+

0 commit comments

Comments
 (0)