ios webView的userContentControlle

2020-03-23  本文已影响0人  Felix的笔头

首先要追溯到写的注册标识符方法那里.......

WKWebViewConfiguration * wkconfiguration = [[WKWebViewConfiguration alloc] init];
// userContentController 强引用了 self (控制器)
[wkconfiguration.userContentController addScriptMessageHandler:self name:@"name"];
如果没有执行对应的removeScriptMessageHandlerForName,就会造成内存泄漏,而如果移除方法写到- (void)dealloc方法里,会出现dealloc方法不走的现象也导致内存泄漏。
解决这种问题有两种方法:
一是:
addScriptMessageHandler: 写到- (void)viewWillAppear:(BOOL)animated { }方法里;
removeScriptMessageHandlerForName:写到- (void)viewWillDisappear:(BOOL)animated{ }方法里。
重点来了。。。
就是因为这样写 导致userContentController:didReceiveScriptMessage:代理方法只在第一次点击的时候会触发,再点击的时候 就会不触发 而且是在某个机型上不是所有的手机都会出现,神奇不 因为移除后跟js的交互就失效了,但是viewWillDisappear并不代表dealloc
所以这种方法不建议

二是:
新建一个类:如 WeakScriptMessageDelegate

#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>



NS_ASSUME_NONNULL_BEGIN

@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>

@property (nonatomic,weak)id<WKScriptMessageHandler> scriptDelegate;

-(instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end

NS_ASSUME_NONNULL_END

#import "WeakScriptMessageDelegate.h"

@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

然后对应改成:
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc] init];
[configuration.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"name"];

文章出处: https://www.jianshu.com/p/7f9e34548676

上一篇下一篇

猜你喜欢

热点阅读