Search code examples
iosswift3nsurlsessionnsurlsessiondatatask

How to "get/download" data/json from a dataTask(with: request)


I want to get the progress of the download of a json file. My current code uses a completion handler that looks like this:

        let dataTask = downloadSession.dataTask(with: request){   
        data,response,error in                                                       

        // do....try here I handle the json file successfully           

        }

        dataTask.resume()

The problem is that I am trying to use URLSessionDataDelegate and the function:

   func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
         displayAlertMessage(message: "Data was received")
    }

The function above never gets call. Based on the research that I have done on the web the reason behind it is that the Handler blocks it and don't let the delegate work the way is supposed to. So how can I solve this issue?

I need the data from the handler but I also want the progress of the download from the URLSessionDataDelegate. What to do? Is there a way to get both?


Solution

  • You can only use one kind of API – either block based or delegate based.

    Consider

    • Is the JSON such a large file that you need a percental progress indicator?
    • Is the indeterminate spinning indicator sufficient?

    In iOS you could simply use isNetworkActivityIndicatorVisible of UIApplication