Browse Source

fix(iOS): WKWebView RetainCycle (#1096)

sunzhongliang 4 years ago
parent
commit
4f4644ffd8
2 changed files with 26 additions and 2 deletions
  1. 5
    0
      ios/RNCWebView.h
  2. 21
    2
      ios/RNCWebView.m

+ 5
- 0
ios/RNCWebView.h View File

@@ -19,6 +19,11 @@
19 19
 
20 20
 @end
21 21
 
22
+@interface RNCWeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>
23
+@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;
24
+- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;
25
+@end
26
+
22 27
 @interface RNCWebView : RCTView
23 28
 
24 29
 @property (nonatomic, weak) id<RNCWebViewDelegate> _Nullable delegate;

+ 21
- 2
ios/RNCWebView.m View File

@@ -162,7 +162,8 @@ static NSDictionary* customCertificatesForHost;
162 162
     wkWebViewConfig.userContentController = [WKUserContentController new];
163 163
 
164 164
     // Shim the HTML5 history API:
165
-    [wkWebViewConfig.userContentController addScriptMessageHandler:self name:HistoryShimName];
165
+    [wkWebViewConfig.userContentController addScriptMessageHandler:[[RNCWeakScriptMessageDelegate alloc] initWithDelegate:self]
166
+                                                              name:HistoryShimName];
166 167
     NSString *source = [NSString stringWithFormat:
167 168
       @"(function(history) {\n"
168 169
       "  function notify(type) {\n"
@@ -187,7 +188,8 @@ static NSDictionary* customCertificatesForHost;
187 188
     [wkWebViewConfig.userContentController addUserScript:script];
188 189
 
189 190
     if (_messagingEnabled) {
190
-      [wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
191
+      [wkWebViewConfig.userContentController addScriptMessageHandler:[[RNCWeakScriptMessageDelegate alloc] initWithDelegate:self]
192
+                                                                name:MessageHandlerName];
191 193
 
192 194
       NSString *source = [NSString stringWithFormat:
193 195
         @"window.%@ = {"
@@ -1077,3 +1079,20 @@ static NSDictionary* customCertificatesForHost;
1077 1079
 }
1078 1080
 
1079 1081
 @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
+