Need to implement timeout mechanism for UIRefreshControl. - iphone

Apple's new UIRefreshControl in iOS 6 is a welcome new feature, but it seems that there is no built-in timeout mechanism.
Here's the scenario why I need it:
Let's say the user pulls the refresh. It goes into the spinning mode, while the code tries to fetch data from the server. The server does not repond and will cause spinning wheel to spin forever. So, there should be a time out mechanism to stop it.
What's the best way to implement it?

First setup a timer with the amount of time you need. Ask it to check the following.
You can use the following property to check whether it is still refreshing after some time
#property (nonatomic, readonly, getter=isRefreshing) BOOL refreshing
If it is then you can stop it using
endRefreshing
Something like :
-(void)checkAndStop{
if(refreshControl.refreshing == YES)
// show an alert if you want
[refreshControl endRefreshing];
}

Also consider using dispatch_after, which might be less consumable than creating NSTimer.
int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
code to be executed on the main queue after delay
});

I have implemented using NSTimer to end the refreshing:
[NSTimer scheduledTimerWithTimeInterval:60 target:self selector:#selector(handleDataRefreshFailure:) userInfo:nil repeats:NO];

Swift version:
let delayInSeconds: UInt64 = 2
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * NSEC_PER_SEC))
dispatch_after(popTime, dispatch_get_main_queue(), {
if refreshControl.refreshing {
refreshControl.endRefreshing()
}
})

Related

How do I schedule a method to run after a delay

I want to be able to setup a timer to count for 23 seconds then perform a function. How could I do this? Would I need NSTimer?
Just use
[NSTimer scheduledTimerWithTimeInterval:23.0 target:self selector:#selector(myThingToDo) options:nil];
Typed on mobile, test first.
Also, there's a neat category available that allows you to use NSTimer with Blocks!
You could use GCD methods directly, which saves having to write a separate callback function:
// Just for clarity I'm defining the time period separately, 23 seconds from now.
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, 23 * NSEC_PER_SEC);
dispatch_after(delay, dispatch_get_main_queue(), ^{
// Anything in here will be run on the main queue 23 seconds from now.
});

Multiple action using selector after delay

Is there a way to do multiple actions respectively using the : performSelector:withObject:afterDelay code ?
Sample code will be appreciated ,
Thanks in advance.
Or use blocks. If you start to type dispatch_after, you'll see code completion that will pop up the following snippet of code, and then you can put however many actions you want in that block. In this example, I'm showing it being used inside an IBAction:
- (IBAction)pushedSomeButton:(id)sender
{
// anything you want to do immediate, do here
[self doingSomethingRightNow];
// anything you want to defer for some time, do inside the dispatch_after block
// in this example, calling callAnotherMethod and whyNotCallAnotherMethod
int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self callAnotherMethod];
[self whyNotCallAnotherMethod];
});
}
Setup a method that gets fired with the performSelector:withObject:afterDelay: call:
-(void)performTheseAction {
// do something
// do something else
[self callAnotherMethod];
[self whyNotCallAnotherMethod];
}

Delay part of iPhone method

I have a method that takes several params, I need to delay a portion of that method. I DO NOT want to split it into several methods and use [self performSelectorAfterDelay] because the delay requires params already in that method. I need something like the following
-(void)someMethod{
.....
delay {
more code but not a separate self method
}
... finish method
}
The dispatch_after function seems to line up with what you need:
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
// this code is going to be executed, on the main queue (or thread) after 2.0 seconds.
});
Of course, the time is configureable, and it's a bit confusing to read at first, but once you get used to how blocks work in conjunction with objective-c code, you should be good to go.
One word of caution:
NEVER, NEVER, NEVER! Block the main thread of an iPhone app using sleep(). Just don't do it!
Looks like an overkill.
-(void)someMethod{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSLog(#"Start code");
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_sync(backgroundQueue, ^{
sleep(5);
// delayed code
NSLog(#"Delayed code");
});
dispatch_sync(backgroundQueue, ^{
// finishing code
NSLog(#"Finishing code");
});
});
}
backgroundQueue might be user at external dispatch call. It looks really bad though :)

How can I trigger a method every 10 seconds without using NSTimer?

I would like to call a method every 10 seconds, but I want to use something other than NSTimer. What could I use to do this?
I know you said you didn't want to use timers, but just to make sure you know how simple it would be with a timer...
[NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:#selector(someMethod)
userInfo:nil
repeats:YES];
If you dont want to use the timer, you can use GCD which internally will make use of NSOperationQueue, nevertheless will work in all cases. For eg: i had a class which was inherited from NSOperation so the above methods didn't work so i had go go with GCD:
double delayInSeconds = 3.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(popTime, queue, ^{
[self methodYouWantToCall];
});
The above code calls the method methodYouWantToCall after every three seconds.
You can create a loop with performSelector:withObject:afterDelay: setting afterDelay to 10.0.
I don't recommend this though, use an NSTimer.
- (void)callMeEvery10Seconds
{
[self performSelector:#selector(callMeEvery10Seconds)
withObject:nil
afterDelay:10.0];
// ... code comes here ...
}
If you are not using Cocos2D, you have to use a NSTimer to do this....
If you are using Cocos2D, use the schedule method
here's a link below that shows both :
How can I create a count down timer for cocos2d?
The easiest way to do so is:
- (void)scheduleLoopInSeconds:(NSTimeInterval)delayInSeconds
{
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(popTime, queue, ^{
[self callWhatEverMethodYouWant];
[self shceduleLoopcaInSeconds:delayInSeconds];//set next iteration
});
}
// now whenever you like call this, and it will be triggering "callWhatEverMethodYouWant" every 10 secs.
[self shceduleLoopcaInSeconds:10.0];

Objective C equivalent to javascripts setTimeout?

I was wondering whether there is a solution to raise an event once after 30 seconds or every 30 seconds in CocoaTouch ObjectiveC.
The performSelector: family has its limitations. Here is the closest setTimeout equivalent:
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.5);
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
// do work in the UI thread here
});
EDIT:
A couple of projects that provide syntactic sugar and the ability to cancel execution (clearTimeout):
https://github.com/Spaceman-Labs/Dispatch-Cancel
https://gist.github.com/zwaldowski/955123
There are a number of options.
The quickest to use is in NSObject:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
(There are a few others with slight variations.)
If you want more control or to be able to say send this message every thirty seconds you probably need NSTimer.
Take a look at the NSTimer class:
NSTimer *timer;
...
timer = [[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:#selector(thisMethodGetsFiredOnceEveryThirtySeconds:) userInfo:nil repeats:YES] retain];
[timer fire];
Somewhere else you have the actual method that handles the event:
- (void) thisMethodGetsFiredOnceEveryThirtySeconds:(id)sender {
NSLog(#"fired!");
}
+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
Documentation
You may also want to look at the other NSTimer methods