我有通过WebView管理的授权逻辑:
我检查WebView委托方法中的所有请求(以捕获redirect_uri)shouldStartLoadWithRequest:
。
问题:如何管理在WebView中打开的每个页面请求的服务器响应?
关键是我们在身份验证服务器方面存在一些问题,并且它有时会显示错误页面。因此,我想捕获此类页面并在这种情况下关闭WebView。
通过找到了解决方案WKWebView
。我以与UIWebView
项目中相同的方式进行连接。
然后我实际上使用了WKNavigationDelegate
协议中的2种方法:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
和
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
代码示例:
第一种方法是检查当前请求是否实际上redirect_uri
应由我们处理:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSLog(@"request: %@", navigationAction.request);
// check whether this request should be stopped - if this is redirect_uri (like user is already authorized)
if (...) {
self.webView.navigationDelegate = nil;
// do what is needed to send authorization data back
self.completionBlock(...);
// close current view controller
[self dismissViewControllerAnimated:YES completion:nil];
// stop executing current request
decisionHandler(WKNavigationActionPolicyCancel);
} else {
// otherwise allow current request
decisionHandler(WKNavigationActionPolicyAllow);
}
}
第二种方法是分析服务器的响应,在这里我们可以验证状态码以处理任何错误
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
// filter the responses, in order to verify only the response from specific domain
if ([[NSString stringWithFormat:[[response URL] absoluteString]] containsString:@"some.domain.com/"]) {
NSInteger statusCode = [response statusCode];
// check what is the status code
if (statusCode == 200 ||
statusCode == 301 ||
statusCode == 302) {
// allow response as everything is ok
decisionHandler(WKNavigationResponsePolicyAllow);
} else {
// handle the error (e.g. any of 4xx or any others)
self.webView.navigationDelegate = nil;
// send needed info back
self.completionBlock(...);
// close current view controller
[self dismissViewControllerAnimated:YES completion:nil];
// stop current response
decisionHandler(WKNavigationResponsePolicyCancel);
}
} else {
// current response is not from our domain, so allow it
decisionHandler(WKNavigationResponsePolicyAllow);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句