URLProtocol doesn't get initialized

1.3k Views Asked by At

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.

2

There are 2 best solutions below

5
Lily Ballard On

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

1
Sandro On

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.