WKWebView and NSURLProtocol not working

后端 未结 4 1780
深忆病人
深忆病人 2020-12-02 08:05

When using the old UIWebView you could catch the requests by implementing a custom NSURLProtocol. I us this to handle requests that requires authentication.

I tried

相关标签:
4条回答
  • 2020-12-02 08:22

    WKWebView has a navigationDelegate property. If that delegate is set WKWebView will call the didReceiveAuthenticationChallenge method on that delegate if the method is implemented. You need to place your authentication code in this method. Example:

    - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
        NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:@"bob"
                                                                   password:@"pass"
                                                                persistence:NSURLCredentialPersistenceNone];
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    }
    
    0 讨论(0)
  • 2020-12-02 08:31

    If you're using URLProtocol just for authentication, there is some other way to achieve that.

    Like when u got a error code -1202 from didFailLoad, and make a URLConnection to do the authentication thing, reload the page after.

    Actually I need to using URLProtocol with WKWebView also, lol~

    0 讨论(0)
  • 2020-12-02 08:35

    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:].

    Old answer

    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.

    As of iOS 10.3 SDK, WKWebView is still unable to make use of custom NSURLProtocols using public APIs.


    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.

    0 讨论(0)
  • 2020-12-02 08:45

    Try this approach: https://github.com/WildDylan/WKWebViewWithURLProtocol/tree/master/Example/WKWebViewWithURLProtocol

    It may be uses private API - i'm not sure ;)

    0 讨论(0)
提交回复
热议问题