ios webView的userContentController:代理方法在某些机型下仅走一次

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

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>

@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>
@property (nonatomic,weak)id<WKScriptMessageHandler> scriptDelegate;

  • (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;
    @end

WeakScriptMessageDelegate.m

#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"];

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容