How can a URLProtocol reuse its calling URLSession

A URLProtocol subclass that does a network call can use its own URLSession/Connection object (or NSStream, Core Foundation, etc.). But since URLProtocol objects are generally created to serve a URLSession request, wouldn't it be better to ask that session object for any needed tasks? How can I get a reference to the calling URLSession object so I can create the URLSessionTask objects I need? (Only if the protocol object was created for some reason that didn't involve a session object would I create a private session object.)

Replies

How can I get a reference to the calling URLSession object so I can create the URLSessionTask objects I need?

You can’t. The NSURLProtocol API hasn’t been updated significantly since it was introduced way back in the Mac OS 10.2 era, and it has certainly not been updated to properly integrate with NSURLSession.

What are you using NSURLProtocol for? I generally recommend that folks avoid it wherever possible, and some of the more common use cases have been obviated by other changes in the OS.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

After seeing URLProtocol examples that use local data, generated data, or semi-recursively call Apple's existing HTTP(S) code, I want to make an example that directly makes network calls. Right now, I'm using URLSessionStreamTask, and it's even harder to find samples for that!

After seeing URLProtocol examples that use local data, generated data, or semi-recursively call Apple's existing HTTP(S) code, I want to make an example that directly makes network calls.

Why? That’s just going to encourage folks to use this tech, which doesn’t seem like a good idea to me.

Also, where you planning to support HTTP requests? Or some custom scheme? The former would be particularly tricky because HTTP is really hard (even HTTP 1.1 is much harder than most folks think). If you’re going to continue down this path then implementing some other scheme ([Gopher][rfc1436] anyone?) would definitely make sense.

Right now, I'm using URLSessionStreamTask, and it's even harder to find samples for that!

Indeed. I really should do something about that…

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"