Reputation: 2529
I'm using NSURLSession with a rather inconsistent REST API. The API can take between 1-50 seconds to respond for reasons out of my control.
I want to let the user know that on long waits (say over 10 seconds), that the request is still processing. I do NOT want to timeout or terminate any requests, though I know this is possible with NSURLSession. I simply want to provide a "still working" popup (for which I am using TSMessages to create).
How would I go about timing this, particularly as the requests are running on a background thread?
Upvotes: 0
Views: 1047
Reputation: 2383
You could use 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
}
I would instantiate the NSTimer after you begin the NSURLSessonTask.
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's comment,
If you have scheduled a repeating NSTimer you should invalidate it in either
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
OR the completion block of NSURLSessionTask. If the NSTimer does not repeat there is no need to invalidate it as it will invalidate itself automatically. Note, once an NSTimer has been invalidated it cannot be reused.
Upvotes: 1