Automatic refreshing one method continuously - ios

have written a method for updating which will call itself again and again when we start that activity, as mentioned below. I wants to stop this method function once we get an output (Now, it keeps running even if we get output). Please let me know if there is any possibility to do it.
-(void)reloadMethod{
[self downloadProgressAudio];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self reloadMethod];
});
}

If you need to keep calling this method until you get an output, the you need to include that test, and only call the function again if you don't have any output.
if !outputDataExists {
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self reloadMethod];
});
}

You can use timer here
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(reloadMethod)
userInfo:nil
repeats:YES];
Once you are done with your repeated execution then do this
[timer invalidate];
timer = nil;

Related

How to natively avoid the nesting block for multiple async tasks which must be executed one after the completion of another

Here is the case:
There are more than 3 async tasks. Each one can only be executed after the completion of the previous one. Yes, must be after the completion of the previous one. That's why dispatch group might not be good for this case because it doesn't care about the 'ordering' quite much. What I'm looking for is a good way of writing such code without too much nesting - just similar to what 'promisekit' does to break the nested block.
I also saw some people suggesting 'serial queue'. Well I tried using the code below:
- (void) asyncMethod1WithCompletion: (void(^)())completion
{
int64_t delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(#"async 1 finished");
completion();
});
}
- (void) asyncMethod2WithCompletion: (void(^)())completion
{
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){
NSLog(#"async 2 finished");
completion();
});
}
And I call those methods using serial queue:
dispatch_queue_t serialQueue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(serialQueue, ^{
NSLog(#"async1 started");
[self asyncMethod1WithCompletion:^{
}];
});
dispatch_sync(serialQueue, ^{
NSLog(#"async2 started");
[self asyncMethod2WithCompletion:^{
}];
});
If everything works well, async task 2 should start executing after 5 seconds which is the completion time of async task one
However, the result is not as what I expected:
2016-09-14 18:59:39.853 SerialQueueTest[32002:2292385] async1 started
2016-09-14 18:59:39.854 SerialQueueTest[32002:2292385] async2 started
2016-09-14 18:59:41.854 SerialQueueTest[32002:2292385] async 2 finished
2016-09-14 18:59:45.353 SerialQueueTest[32002:2292385] async 1 finished
Did I write the code wrong? Is there any native way of writing lesser nesting code? If there are 5-6 async tasks and each relies on the result of each other, the code would be very massy. I would even think of one very case: a common login function which also integrates some 3rd party accounts login.
I'm also thinking of using dispatch group in a different way: 1. enter the group and finish the first async task and exit group. 2. inside the dispatch_group_notify block, enter the dispatch group again for second async task. 3. Outside the disptach_group_notify block, calling the second async task and exit the group again. 4. write the second dispatch_group_notify for notifying the completion of the second task.
- (dispatch_group_t) asyncMethod1
{
NSLog(#"async1 started");
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
int64_t delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(#"async 1 finished");
dispatch_group_leave(group);
});
return group;
}
- (dispatch_group_t) asyncMethod2
{
NSLog(#"async2 started");
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
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){
NSLog(#"async 2 finished");
dispatch_group_leave(group);
});
return group;
}
And using:
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
dispatch_group_notify([self asyncMethod1], queue, ^{
[self asyncMethod2];
});
});
dispatch_group_t looks similar there like promise.
As you can see, you can even use concurrent queue.
You can use NSOperationQueue here.
Create n block operations(NSBlockOperation), where n is the number of async operations you have.
Add them in the NSOperationQueue in the order you want them to be executed in.
Set maxConcurrentOperationCount of NSOperationQueue to 1 to make the queue as serial.

dispatch_async timeout method call

Is there a good way to call an external method after a set time limit for completing the long process outlined below? I would like the long process to stop trying after a set interval and call a method to try something else and wrap up the request.
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//// LONG PROCESS
dispatch_async(dispatch_get_main_queue(), ^{
//// RESULTS PROCESS
});
});
In order to "kill" the process that's running your block, you'll have to check a condition. This will allow you to do cleanup. Consider the following modifications:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
BOOL finished = NO;
__block BOOL cancelled = NO;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
if (!finished) {
cancelled = YES;
}
});
void (^cleanup)() = ^{
// CLEANUP
};
//// LONG PROCESS PORTION #1
if (cancelled) {
cleanup();
return;
}
//// LONG PROCESS PORTION #2
if (cancelled) {
cleanup();
return;
}
// etc.
finished = YES;
dispatch_async(dispatch_get_main_queue(), ^{
//// RESULTS PROCESS
});
});
In the ////Long Process change a boolean value (like BOOL finished) to true when finished.
After the call to dispatch_async(...) you typed here, add this:
int64_t delay = 20.0; // In seconds
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^(void){
if (!finished) {
//// Stop process and timeout
}
});
In this way, after 20 seconds (or any time you want) you can check if the process is still loading and take some provisions.
I've used this method for Swift:
let delay = 0.33 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
//// RESULTS PROCESS
}

dispatch_after() with zero pop time

Is it possible to make this "clearer" or "better" ?
Any solution is welcome, even thought i got a right answer.
The problem is dispatch_after() with popTime==0 is still giving time to the main thread to make some UI changes. The following code is sometimes called from a background thread.
-(void)methodCalledFromSomeThread{
if (delayInSeconds) {
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// Updating some UI like
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
// Updating some UI like
});
}
}
dispatch_async on the main queue will also queue the code to run on the next runloop, giving time for the system to update the UI. You can check like so:
void (^block)() = ^{
[self.tableView reloadData];
};
if (delayInSeconds) {
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), block);
}else if([NSThread isMainThread]) {
block();
}
else {
dispatch_async(dispatch_get_main_queue(), block);
}

method not called with dispatch_async and repeating NSTimer

I am developing an app where i want to call method in separate queue using dispatch_async. I want to call that method repeatedly after certain interval of time. But the method is not getting called.
I don't know whats wrong. Here is my code:
dispatch_async( NotificationQueue, ^{
NSLog(#"inside queue");
timer = [NSTimer scheduledTimerWithTimeInterval: 20.0
target: self
selector: #selector(gettingNotification)
userInfo: nil
repeats: YES];
dispatch_async( dispatch_get_main_queue(), ^{
// Add code here to update the UI/send notifications based on the
// results of the background processing
});
});
-(void)gettingNotification {
NSLog(#"calling method ");
}
If you want a repeating timer to be invoked on a dispatch_queue_t, use dispatch_source_create with a DISPATCH_SOURCE_TYPE_TIMER:
dispatch_queue_t queue = dispatch_queue_create("com.firm.app.timer", 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 20ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
// stuff performed on background queue goes here
NSLog(#"done on custom background queue");
// if you need to also do any UI updates, synchronize model updates,
// or the like, dispatch that back to the main queue:
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"done on main queue");
});
});
dispatch_resume(timer);
That creates a timer that runs once every 20 seconds (3rd parameter to dispatch_source_set_timer), with a leeway of a one second (4th parameter to dispatch_source_set_timer).
To cancel this timer, use dispatch_source_cancel:
dispatch_source_cancel(timer);
Try this code
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async( dispatch_get_main_queue(), ^{
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
selector: #selector(gettingNotification) userInfo: nil repeats: YES];
// Add code here to update the UI/send notifications based on the
// results of the background processing
});
});
-(void)gettingNotification {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//background task here
dispatch_async( dispatch_get_main_queue(), ^{
// update UI here
);
});
}
int parameter1 = 12;
float parameter2 = 144.1;
// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
NSLog(#"parameter1: %d parameter2: %f", parameter1, parameter2);
});
look for more
How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

how to call a method of multiple arguments with delay

I'm trying to call a method after some delay.
I know there is a solution for that:
[self performSelector:#selector(myMethod) withObject:nil afterDelay:delay];
I saw this question and Documentation
But my question is: How can I call a method that takes two parameters??
for instance:
- (void) MoveSomethigFrom:(id)from To:(id)to;
How would I call this method with delay, using performSelector:withObject:afterDelay:
Thanks
use dispatch_after:
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){
//code to be executed on the main queue after delay
[self MoveSomethingFrom:from To:to];
});
EDIT 2015: For Swift, i recommend using this small helper method: dispatch_after - GCD in swift?
You can also implement method in NSObject's category using NSInvocation object (works in all versions of iOS). I guess it should be something like this:
#interface NSObject(DelayedPerform)
- (void)performSelector:(SEL)aSelector withObject:(id)argument0 withObject:(id)argument1 afterDelay:(NSTimeInterval)delay {
NSMethodSignature *signature = [self methodSignatureForSelector:aSelector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:aSelector];
[invocation setArgument:&argument0 atIndex:2];
[invocation setArgument:&argument1 atIndex:3];
[invocation performSelector:#selector(invoke) withObject:nil afterDelay:delay];
}
#end
Other ideas:
1)
You could use NSInvocations:
+ (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)signature
(>> see Eldar Markov's answer)
Documentation:
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSInvocation_Class/Reference/Reference.html
2) You could use a helper method..
[self performSelector:#selector(helperMethod) withObject:nil afterDelay:delay];
- (void) helperMethod
{
// of course x1 and x2 have to be safed somewhere else
[object moveSomethigFrom: x1 to: x2];
}
3) You could use an array or a dictionary as parameter..
NSArray* array = [NSArray arrayWithObjects: x1, x2, nil];
[self performSelector:#selector(handleArray:) withObject:array afterDelay:delay];
- (void) handleArray: (NSArray*) array
{
[object moveSomethigFrom: [array objectAtIndex: 0] to: [array objectAtIndex: 1]];
}
Swift:
let delayInSeconds = 3.0;
let delay = delayInSeconds * Double(NSEC_PER_SEC)
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay));
dispatch_after(popTime, dispatch_get_main_queue(), {
// DO SOMETHING AFTER 3 sec
});
Here is how you can trigger a block after a delay in Swift:
runThisAfterDelay(seconds: 5) { () -> () in
print("Prints this 5 seconds later in main queue")
//Or perform your selector here
}
/// EZSwiftExtensions
func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), after)
}
The argument count does not really matter.
Its included as a standard function in my repo:
https://github.com/goktugyil/EZSwiftExtensions
These will all work, but are all much more complex than is needed.
Design the method to be called with an NSDictionary argument. Put the objects in it you need.
If you want the method to be accessible by other means as well, call instead a method that 'unwraps' the dictionary and calls the intended method with explicit parameters.

Resources