ios - 在 NSURLSession 上设置一个计时器

标签 ios objective-c rest nstimer nsurlsession

我正在使用 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/

相关文章:

ios - cocoapods 的代码/测试覆盖工具?

objective-c - 简单的 addObject 到 NSMutableArray 方法给出 lldb 错误

objective-c - 为什么 UIView.exclusiveTouch 不起作用?

objective-c - 在 Objective-C 上 : which is the root directory in iphone

java - GWT RPC 安全、http header 、身份验证和 requestbuilder

rest - 在 RESTful 响应中包含聚合信息时的 URI

ios - MonoTouch 中的 AesCryptoServiceProvider

ios - 应用程序启动时显示 EULA,如果用户不接受则退出

ios - 将数据分配给 Collection View 后从服务器获取数据

rest - 为什么在PowerShell中用椭圆修剪我的REST输出?