如何确定 NSURLSessionTask 的请求何时开始? [英] How to determine when NSURLSessionTask's request begins?

查看:95
本文介绍了如何确定 NSURLSessionTask 的请求何时开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 NSURLSessionTasks 并且我正在尝试监视我的某些 HTTP 请求需要多长时间,当 NSURLSessionTask 实际上是发出初始请求?如果这是 NSOperation 中的 NSURLConnection,我只会在开始请求时启动一个计时器,但我无法控制任务何时开始.

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.

推荐答案

请检查 NSURLSessionTaskDelegate.它具有以下委托回调:

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:

计算时间间隔.

选项 01 [近似值]:

您应该在调用 resume 方法后立即启动一个计时器,并计算何时调用委托回调 didCompleteWithError.

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];

选项 02 [如果需要准确性]:

NSURLSessionTask 的属性都是 KVO 兼容的.

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, */
}

这篇关于如何确定 NSURLSessionTask 的请求何时开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆