Is there a way to get the URLSession that a URLSessionTask is sourced from?

Exactly as the (current) subject says. We can use

URLSession
objects to create various tasks, subclasses of
URLSessionTask
. But if you only have a reference to a task, is there some sort of property to get a reference to its source session?


This is a variant of a question I postedlong ago.

Replies

There isn’t a way to do this directly. Most folks don’t need to do this because they have a limited set of sessions, with each session having its own unique purpose. Thus, when dealing with a task you already know the context necessary to find its session.

If you’re dealing with an arbitrary mix of sessions and tasks, you could solve this problem by tagging each task with an identifier for looking up the session.

taskDescription
is a good way to do this [1]. Another option is to associate a custom value with the task’s request using the
URLProtocol
property APIs,
setProperty(_:forKey:in:)
and friends.

Share and Enjoy

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

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

[1] The documentation indicates that this is intended to be a user-visible value but that’s not actually the case. I’m going to go fix that now (q. 128150).

An app-specific out-of-band method of connecting a task back to its originating session can't be used by a library (which I eventually want for this code I'm thinking of writing). And since tasks can only be obtained via an owing session, an explicit back-link makes sense.


Feedback Assistant radar: FB7221595 ("Add accessor from URLSessionTask to URLSession")

And since tasks can only be obtained via an owing session, an explicit back-link makes sense.

Fair enough.

Feedback Assistant radar: FB7221595 ("Add accessor from URLSessionTask to URLSession")

Thanks.

An app-specific out-of-band method of connecting a task back to its originating session can't be used by a library (which I eventually want for this code I'm thinking of writing).

I don’t understand where you’re going here. Most libraries that use

URLSession
tasks have their own session. It’s rare for library code to work with client-provided tasks from arbitrary client-owned sessions. Can you explain more how that comes about in your library?

Share and Enjoy

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

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