iosobjective-cnsurlsessionnsurlsessiontask

How to determine when NSURLSessionTask's request begins?


I use NSURLSessionTasks and I'm trying to monitor how long some of my HTTP Requests take, what delegate method (or something else) can I monitor for when the NSURLSessionTask actually makes the initial request? If this were a NSURLConnection inside an NSOperation I'd just start a timer when I start the request but I don't have control over when tasks start.


Solution

  • Please check NSURLSessionTaskDelegate. It has following delegate callbacks:

    URLSession:task:didCompleteWithError:
    URLSession:task:didReceiveChallenge:completionHandler:
    URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:
    URLSession:task:needNewBodyStream:
    URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:
    

    To calculate time interval.

    Option 01 [Approximate]:

    You should start a timer just after the call to resume method and and calculate when the delegate callback didCompleteWithError is invoked.

    self.dataTask = [self.session dataTaskWithRequest:theRequest];
    [self.dataTask resume];
    
    NSTimeInterval totalCountdownInterval;
    NSDate* startDate = [NSDate date];
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkCountdown:) userInfo:nil repeats:YES];
    

    Option 02 [If accuracy is desired]:

    NSURLSessionTask’s properties are all KVO-compliant.

    [self.dataTask addObserver:self forKeyPath:@"someKeyPath" options:NSKeyValueObservingOptionOld context:nil];
    [self.dataTask resume];
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
      // do some calculation after checking state
    
       /* 
    NSURLSessionTaskStateRunning = 0,                     
        NSURLSessionTaskStateSuspended = 1,
        NSURLSessionTaskStateCanceling = 2,                   
        NSURLSessionTaskStateCompleted = 3, */
    }