Andrey M. Andrey M. - 2 years ago 104
Swift Question

How to loop despatch_after

I want to loop dispatch_after for looping showing images like this:

while isRunning {
let delay = Int64(Double(NSEC_PER_SEC) * settings.delay)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay), dispatch_get_main_queue(), {
dispatch_async(dispatch_get_main_queue(), {

It supposed to call
seconds. But it stucks in infinite loop without showing images. I dont know how to solve this problem. Any help is appreciated.

Answer Source

Loop is dispatching infinite dispatch_after because isRunning is yes and loop is not waiting , better to put some count (i<10) or use NSTimer to certain condition then invalidate.

if (self.stimerShowNextImage.isValid) {

        [self.stimerShowNextImage invalidate];
        self.stimerShowNextImage = nil;

    self.stimerShowNextImage = [NSTimer scheduledTimerWithTimeInterval: 5
                                                                 target: self
                                                               selector: @selector(showNextImage)
                                                               userInfo: nil
                                                                repeats: YES];

Above is the timerCode with 5 second delay , in ViewWillDisapper you need to invalidate it , Also before scheduling timer you need to check its not already running.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download