How to Trigger a Block After a Delay in iOS Development

How to Trigger a Block After a Delay in iOS Development

6 June 2024 Stephan Petzl Leave a comment Tech-Help

In iOS development, there are situations where you might need to execute a block of code after a certain delay. This can be useful for tasks such as animations, delayed actions, or scheduled updates. In this guide, we will explore various methods to trigger a block after a delay using both Objective-C and Swift.

Using dispatch_after in Objective-C

The dispatch_after function from Grand Central Dispatch (GCD) is a commonly used method to execute a block after a delay. Below is an example of how to use dispatch_after:

CGFloat time1 = 3.49;
CGFloat time2 = 8.13;

// Delay 2 seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGFloat newTime = time1 + time2;
    NSLog(@"New time: %f", newTime);
});

In this example, we delay the execution of the block by 2 seconds. The block captures the values of time1 and time2 from the local scope and logs their sum.

Using DispatchQueue.main.asyncAfter in Swift

For Swift developers, the DispatchQueue.main.asyncAfter method provides a similar functionality. Here’s an example in Swift:

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}

This Swift example demonstrates how to delay the execution of a block by 2 seconds. The block captures the values of time1 and time2 and prints their sum.

Creating a Custom Delay Function in Swift

If you frequently need to delay blocks of code, you can create a custom function to simplify the process. Here’s an example of a custom delay function in Swift:

func performBlock(block: @escaping () -> Void, afterDelay delay: TimeInterval) {
    DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: block)
}

// Usage
performBlock({
    // Perform actions
}, afterDelay: 0.3)

This custom function allows you to specify a delay in seconds and a block to execute after the delay. It improves code readability and reusability.

Advanced Techniques

For more advanced scenarios, you can encapsulate these delay methods into utility classes or categories. For example, you can create a category on NSObject to add delay functionality:

#import 

@interface NSObject (Blocks)

- (void)performBlock:(void (^)())block afterDelay:(NSTimeInterval)delay;

@end

@implementation NSObject (Blocks)

- (void)performBlock:(void (^)())block {
    block();
}

- (void)performBlock:(void (^)())block afterDelay:(NSTimeInterval)delay {
    void (^block_)() = [block copy];
    [self performSelector:@selector(performBlock:) withObject:block_ afterDelay:delay];
}

@end

// Usage
[anyObject performBlock:^{
    [anotherObject doYourThings:stuff];
} afterDelay:0.15];

This category allows you to use a method similar to performSelector:withObject:afterDelay: but with blocks.

Conclusion

Delaying the execution of blocks in iOS development can be easily achieved using dispatch_after in Objective-C and DispatchQueue.main.asyncAfter in Swift. For frequent use, creating custom delay functions or utility classes can enhance code readability and maintainability.

For mobile developers looking to automate testing without delving into complex coding, consider using Repeato. Repeato is a no-code test automation tool for iOS and Android that allows you to create, run, and maintain automated tests efficiently. It leverages computer vision and AI, enabling even non-technical team members to handle test automation, allowing developers to focus more on creating great products.

Like this article? there’s more where that came from!