NSURLSession dataTaskWithRequest not being called

2019-03-06 03:39发布

问题:

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?

回答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).



回答2:

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.