我使用NSURLSessionTask
s,并且尝试监视一些HTTP请求花费多长时间,在NSURLSessionTask
实际发出初始请求时可以监视什么委托方法(或其他方法)?如果这是NSURLConnection
内部,NSOperation
我将在启动请求时启动计时器,但无法控制任务启动的时间。
请检查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, */
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句