1

I am implementing an URLProtocol in an app.

import Cocoa

class MyURLProtocol: URLProtocol {

    override init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
        super.init(request: request, cachedResponse: cachedResponse, client: client)
    }

    override class func canInit(with request: URLRequest) -> Bool {
        return true
    }

    override class func canonicalRequest(for request: URLRequest) -> URLRequest {
        return request
    }

    override func startLoading() {
        print("loading")
    }
}

Although canInit(with request: URLRequest) always returns true, neither init(…) nor canonicalRequest(…) nor startLoading() get called.

URLProtocol.registerClass for MyURLProtocol is called in willFinishLaunching in the AppDelegate

I don't know what to do. Yesterday, day code called at least the functions.

Thanks for your help.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Sandro
  • 84
  • 5

2 Answers2

3

Are you using URLSession? URLSession bypasses the normal protocol registration and instead has you explicitly configure the protocols in the URLSessionConfiguration. See URLSessionConfiguration.protocolClasses.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • No. I am only loading an URLRequest in a WKWebView. – Sandro Sep 25 '17 at 21:16
  • I need to handle differnt url schemes in my app – Sandro Sep 25 '17 at 21:17
  • I also implement the WKNavigationDelegate and func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) gets called with an unsupported url error. – Sandro Sep 25 '17 at 21:52
  • 1
    `WKWebView` is an out-of-process webview. It's impossible to have `WKWebView` use your `URLProtocol` subclass because it's running in the wrong process. If you want to use `URLProtocol` with web views, you need to use the old in-process `UIWebView` class instead. – Lily Ballard Sep 25 '17 at 22:10
  • Huh, it turns out that iOS 11 actually adds a new API that might do what you want. `WKWebViewConfiguration` has a new method `setURLSchemeHandler(_:forURLScheme:)` and some related protocols to allow you to implement custom schemes across the process boundary. This still isn't `URLProtocol` but it should do effectively the same thing. – Lily Ballard Sep 25 '17 at 22:12
1

Actually I'am working on a macOS app and not an iOS one, but it has fixed the problem when I was changing from WKWebView to WebView.

Thanks to Kevin Ballard on his comment.

Sandro
  • 84
  • 5