0

I have a second NSURLSession that is being called directly from the completionHandler of the previous one (it is dependent on the cookies generated from the first call). It worked for a while and sometimes still works, but most of the time does not. When I set through the debugger, it simply goes from the dataTaskWithRequest line to the line past the task.resume() call. Any thoughts?

func getDates () -> [NSDate] {
    var urlDays = NSURL(string: "https://mycorrecturl.com")
    var requestDays = NSMutableURLRequest(URL: urlDays!)
    let sessionDays = NSURLSession.sharedSession()

    // Create array of NSDate objects
    var allDates = [NSDate]()

    var task = sessionDays.dataTaskWithRequest(requestDays, completionHandler: {data, response, error -> Void in

        // Convert into array of NSDate objects

    })
    task.resume()
    return allDates
}

Why would this this dataTaskWithRequest function just not fire?

syntheticgio
  • 588
  • 6
  • 25

2 Answers2

1

The problem that you are facing is that dataTaskWithRequest is an asynchronous call, that's the reason why you receive an empty array (that's only chance that finish and return a the same time and sometimes you receive data).

For that, you need to use a closure that get's call from the closure of dataTaskWithRequests.

Like this (here I only show you the declaration method with a closure):

func getDates (success:([NSDate])->Void){

And in the body of your network call:

var task = sessionDays.dataTaskWithRequest(requestDays, completionHandler: {data, response, error -> Void in

    // Convert into array of NSDate objects
    var yourArrayOfNSDateConverted:[NSDate] = [NSDate]()
    success(yourArrayOfNSDateConverted)
})

Obviously the yourArrayOfNSDateConverted contains your process the data and also you need to manage the error (for that you can add another closure).

-1

Looks like it is firing, I just wasn't waiting long enough. The function returned back to the calling function with no data, but thats because the NSURLSession wasn't finished yet. I guess I'm still getting the hang of the asynchronous nature of NSURLSession.

syntheticgio
  • 588
  • 6
  • 25
  • A minute or two. But I think it varies - I haven't been timing it since its been working, my whole program can take upwards of 10 minutes so its hard to say. – syntheticgio Mar 08 '15 at 04:07
  • How have you fixed it? – Kaptain Sep 08 '15 at 16:20
  • @Kaptain completely missed your question, sorry (I know it is way late now). But yeah the code above worked fine it was just that the server request took a while to respond with the data. A better solution if I would have pursued this further would have been to break up the request into multiple requests of smaller amounts of data. So instead of requesting all dates (in this example) I might request three months worth at a time and handle each chunk separately. – syntheticgio May 29 '16 at 21:44