Search code examples
iosmacosnsurlsessionfoundation

URLSession best practice - multiple requests


I need a little guidance on best practice with URLSession/NSURLSession.

My requirement stipulates that I have to do adhoc/periodic HTTP GET requests. i.e. Every few mins, then maybe every 30 seconds, changing at will.

Anyway I've achieved this as follows, I have a method that contains code like this:

 let urlRequest = URLRequest(url: url)

        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        // make the request
        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in ...

That keeps the the URLSession within the scope of this method.

So some questions:

1) is this the right way to achieve what I'm looking for or should I have a URLSession at Class level scope and create multiple 'tasks'? - if so should I called .resume on each task?

2) if this is an acceptable usage paradigm for URLSession am I leaking memory (don't think so with ARC)? I ask as I've noticed that the URLSession object seems to stay around outside the scope of the method where I call it/replace it each time. (I check this with a WEAK reference to the object that I periodically inspect)...

3) is there a neater way to GET request the same URL on an adhoc basis with URLSession? I feel NSURLConnection handled this well but its deprecated.


Solution

  • 1) is this the right way to achieve what I'm looking for or should I have a URLSession at Class level scope and create multiple 'tasks'? - if so should I called .resume on each task?

    answer: What you are doing is not incorrect, though it is uncommon. The best practice would be to use URLSession's shared instance. Creating a new session configuration and URLSession object for each request that you are making (as often as every 30 seconds), would be less performant than using the singleton.

    2) if this is an acceptable usage paradigm for URLSession am I leaking memory (don't think so with ARC)? I ask as I've noticed that the URLSession object seems to stay around outside the scope of the method where I call it/replace it each time. (I check this with a WEAK reference to the object that I periodically inspect)...

    answer: the reason that you may notice that your URLSession object is living beyond the scope of your method call is the you are passing it an escaping closure and the session will likely live until the completion handler is called.

    3) is there a neater way to GET request the same URL on an adhoc basis with URLSession? I feel NSURLConnection handled this well but its deprecated.

    answer: There are many ways to accomplish this. You might try storing a reference to either the URL or the request, and call your method with the same request as you wish.