I use NSURLSessionTask
s 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.
3 回答
请检查NSURLSessionTaskDelegate。它有以下委托回调:
URLSession:task:didCompleteWithError:
URLSession:task:didReceiveChallenge:completionHandler:
URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:
URLSession:task:needNewBodyStream:
URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:
计算时间间隔。
选项 01 [近似值]:
您应该在调用 resume 方法后立即启动一个计时器,并计算调用委托回调 didCompleteWithError 的时间。
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 兼容的。
[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, */
}
我知道这是一个老问题,但对于那些在 URLSessionTaskDelegate 上搜索委托方法 func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) 的人来说,应该能够提供有关请求的大量信息,包括花了多长时间。
两种选择:
如果需要,您可以实现基于委托的再现,然后捕获和
NSURLSession
之间经过的时间。诚然,这并没有捕捉到接收响应所涉及的延迟,但如果您正在寻找一种简单的方法来计算等待可用连接的时间,那么这是一种方法。didReceiveResponse
didCompleteWithError
另一种方法是将
NSURLSessionTask
对象包装在NSOperation
子类中,就像您对NSURLConnection
. 在您使用NSURLSessionTask
工厂方法的完成块再现的情况下,这是微不足道的。使用基于委托的方法时有点麻烦(因为,令人恼火的是,NSURLSession
不允许我们为单个任务指定委托对象(即使它们让我们为它们关联完成块),而是所有特定于任务的委托方法在会话对象级别调用)。无论如何,当你将它包装在一个
NSOperation
子类中时,你可以很容易地捕捉到你完整的经过时间。