ios WKWebView JS 交互 + 进度条

原文地址: http://www.jianshu.com/p/ab58df0bd1a1

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

configuration.allowsInlineMediaPlayback = YES;                  // 允许播放声音

configuration.mediaPlaybackRequiresUserAction = false;

WKUserContentController *userContentController = [[WKUserContentController alloc] init];

[userContentController addScriptMessageHandler:self name:@"JS端方法名称1"];

[userContentController addScriptMessageHandler:self name:@"JS端方法名称2"];

configuration.userContentController = userContentController;

WKPreferences *preferences = [WKPreferences new];

preferences.javaScriptCanOpenWindowsAutomatically = YES;

preferences.minimumFontSize = 40.0;

configuration.preferences = preferences;

// 1、设置webview

WKWebView *wkWebview = [[WKWebView alloc] initWithFrame:_frame configuration:configuration];

// 加载进度条

[wkWebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

wkWebview.UIDelegate = self;

wkWebview.navigationDelegate = self;

NSURLRequest *verifyRequest = [NSURLRequest requestWithURL:url];

[self.view addSubview:wkWebview];

//进度条

UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 3)];

progress.backgroundColor = [UIColor clearColor];

[self.view addSubview:progress];

CALayer *layer = [CALayer layer];

layer.frame = CGRectMake(0, 0, 0, 3);

layer.backgroundColor = [UIColor blueColor].CGColor;

[progress.layer addSublayer:layer];

_progresslayer = layer;

[wkWebview loadRequest:verifyRequest];


// 进度条

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context

{

if ([keyPath isEqualToString:@"estimatedProgress"]) {

_progresslayer.opacity = 1;

if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {

return;

}

_progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);

if ([change[@"new"] floatValue] == 1) {

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

_progresslayer.opacity = 0;

});

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

_progresslayer.frame = CGRectMake(0, 0, 0, 3);

});

}

}else{

[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

}

}

#pragma mark -- WKScriptMessageHandler

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message

{

//JS调用OC方法

//message.boby就是JS里传过来的参数

NSLog(@"body:%@",message.body);

if ([message.name isEqualToString:@"JS端方法名称1"]) {

// 该方法要调用的代码


} else if ([message.name isEqualToString:@"JS端方法名称2"]) {

// 该方法要调用的代码

}


}




注意点:

1、遵守协议 全局变量啥的不说了

2、后端 调用方法  要按照  window.webkit.messageHandlers.方法名.postMessage(需要回传给iOS端的参数,可选)  格式,不然无法调用

你可能感兴趣的:(ios WKWebView JS 交互 + 进度条)