WKWebView causes my view controller to leak

后端 未结 6 1938
礼貌的吻别
礼貌的吻别 2020-12-12 11:52

My view controller displays a WKWebView. I installed a message handler, a cool Web Kit feature that allows my code to be notified from inside the web page:

o         


        
6条回答
  •  感情败类
    2020-12-12 12:46

    The solution posted by matt is just what's needed. Thought I'd translate it to objective-c code

    @interface WeakScriptMessageDelegate : NSObject
    
    @property (nonatomic, weak) id scriptDelegate;
    
    - (instancetype)initWithDelegate:(id)scriptDelegate;
    
    @end
    
    @implementation WeakScriptMessageDelegate
    
    - (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
    

    Then make use of it like this:

    WKUserContentController *userContentController = [[WKUserContentController alloc] init];    
    [userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"name"];
    

提交回复
热议问题