我正在使用 NSURLSession 和一个相当不一致的 REST API。由于我无法控制的原因,API 可能需要 1-50 秒才能做出响应。
我想让用户知道在长时间等待(比如超过 10 秒)时,请求仍在处理中。我不想超时或终止任何请求,尽管我知道这可以通过 NSURLSession 实现。我只是想提供一个“仍在工作”的弹出窗口(我正在使用 TSMessages 创建)。
我将如何进行计时,特别是当请求在后台线程上运行时?
最佳答案
您可以使用NSTimer
。
Creates and returns a new NSTimer object and schedules it on the current run loop in the default mode. After seconds seconds have elapsed, the timer fires, sending the message aSelector to target.
// Schedule a timer for 10 seconds and then call the method alertUser:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(alertUser:) userInfo:nil repeats:NO];
- (void)alertUser:(id)sender
{
// Alert the user
}
我会在你开始 NSURLSessonTask 后实例化 NSTimer。
EG
self.dataTask = [self.session dataTaskWithRequest:theRequest];
[self.dataTask resume];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(alertUser:) userInfo:nil repeats:NO];
根据@Rob 的评论,
如果您安排了重复的 NSTimer,您应该在其中之一中使其无效
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
OR NSURLSessionTask 的完成 block 。如果 NSTimer 不重复,则无需使其失效,因为它会自动失效。请注意,一旦 NSTimer 失效,就无法重复使用。
关于ios - 在 NSURLSession 上设置一个计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21512460/