• iOS 添加WKWebView导致控制器无法释放的问题


    在WkWebView与JavaScript交互中,经常会在原生中注入MessageHandler,app中注入MessageHandler的方法

        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.userContentController = [WKUserContentController new];
        //注入handler
        [config.userContentController addScriptMessageHandler:self name:@"HandlerName"];
    

    这里我们发现在向JS中注入handler的时候强引用了self,最终导致内存泄漏

    解决方法 添加一个新类 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
    

    使用 添加了下面这行代码之后ViewController就会调用dealloc方法,此时ViewController已经正常释放。但是WeakScriptMessageDelegate没有释放,需要在dealloc中将WeakScriptMessageDelegate释放掉。

        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.userContentController = [WKUserContentController new];
        //注入handler
        [config.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"HandlerName"];
    

    释放WeakScriptMessageDelegate 在dealloc方法中实现

        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"HandlerName"];
    
    
  • 相关阅读:
    实现毛玻璃效果
    iOS-调用系统的短信和发送邮件功能,实现短信分享和邮件分享
    集成环信
    HTTP 方法:GET 对比 POST
    虚拟DOM
    javascript的回调函数 同步 异步
    jQuery中的Deferred和promise
    web性能
    JSONP
    java
  • 原文地址:https://www.cnblogs.com/qqcc1388/p/8487052.html
Copyright © 2020-2023  润新知