在NSURLSession上设置计时器

时间:2014-02-02 15:38:42

标签: ios objective-c rest nstimer nsurlsession

我正在使用具有相当不一致的REST API的NSURLSession。 API可能需要1-50秒才能响应我无法控制的原因。

我想让用户知道在长时间等待(例如超过10秒),请求仍在处理中。我不想超时或终止任何请求,但我知道这可以通过NSURLSession实现。我只是想提供一个“仍在工作”的弹出窗口(我正在使用TSMessages创建)。

我如何计时,特别是当请求在后台线程上运行时?

1 个答案:

答案 0 :(得分:1)

您可以使用NSTimer

  

创建并返回一个新的NSTimer对象并在其上安排它   默认模式下的当前运行循环。几秒钟之后   经过,计时器触发,将消息aSelector发送到目标。

    // 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。

E.G。

self.dataTask = [self.session dataTaskWithRequest:theRequest];

[self.dataTask resume];

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(alertUser:) userInfo:nil repeats:NO];

Per @ Rob的评论,

如果您已安排重复的NSTimer,则应在

中使其无效
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

或NSURLSessionTask的完成块。如果NSTimer没有重复,则不需要使其无效,因为它会自动使自身无效。请注意,一旦NSTimer失效,就无法重复使用。