NSURLSession dataTaskWithRequest not being called

前端 未结 2 1361
[愿得一人]
[愿得一人] 2021-01-27 06:06

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 wor

相关标签:
2条回答
  • 2021-01-27 06:38

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

    0 讨论(0)
  • 2021-01-27 06:55

    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.

    0 讨论(0)
提交回复
热议问题