问题描述
使用旧的 UIWebView 时,您可以通过实现自定义 NSURLProtocol 来捕获请求.我用它来处理需要身份验证的请求.
When using the old UIWebView you could catch the requests by implementing a custom NSURLProtocol. I us this to handle requests that requires authentication.
我尝试了相同的代码,但它不适用于新的 WKWebView,但我的协议类根本没有被调用.有人遇到同样的问题还是有更好的方法来使用 WKWebView 进行身份验证?
I tried the same code and it doesn't work with the new WKWebView but my protocol class isn't called at all. Is someone experiencing the same problem or is there a better way of doing authentication with the WKWebView?
在没有任何修改的情况下,我在 decisionPolicyForNavigationResponse 委托函数中得到了 401 响应.我还尝试使用 NSURLConnection 连接到服务器并使用 NSURLConnectionDataDelegate 处理身份验证.这可行,但 WKWebView 不会获取存储的凭据.
Without any modifications I get a 401 response in the decidePolicyForNavigationResponse delegate function. I've also tried connection to the server with a NSURLConnection and handling the authentication with a NSURLConnectionDataDelegate. That works but the stored credentials isn't picked up by the WKWebView.
推荐答案
iOS 11 和 macOS 10.13 的更新答案
从iOS 11开始可以声明一个符合WKURLSchemeHandler
协议的对象,并在WKWebView
配置中注册:-[WKWebViewConfiguration setURLSchemeHandler:forURLScheme:]
.
Updated answer for iOS 11 and macOS 10.13
Since iOS 11 it is possible to declare an object that conforms to the WKURLSchemeHandler
protocol and register it in the WKWebView
configuration: -[WKWebViewConfiguration setURLSchemeHandler:forURLScheme:]
.
WKWebView
发出请求并在进程外呈现内容,这意味着您的应用不会听到它们发出的请求.如果您缺少某个功能,现在是时候向 Apple 提交错误报告和/或改进请求了.
WKWebView
makes requests and renders content out-of-process, meaning your app does not hear the requests they make. If you are missing a functionality, now is the time to open a bug report and/or an enhancement request with Apple.
从 iOS 10.3 SDK 开始,WKWebView
仍然无法通过公共 API 使用自定义 NSURLProtocol
.
As of iOS 10.3 SDK, WKWebView
is still unable to make use of custom NSURLProtocol
s using public APIs.
有进取心的开发者发现了一个有趣的方法:+[WKBrowsingContextController registerSchemeForCustomProtocol:]
它应该将提供的方案添加到自定义协议处理方案列表中,然后应该与 NSURLProtocol
一起使用.
Enterprising developers have found an interesting method:
+[WKBrowsingContextController registerSchemeForCustomProtocol:]
It supposedly adds the provided scheme to a list of custom protocol handled schemes and should then work with NSURLProtocol
.
这篇关于WKWebView 和 NSURLProtocol 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!