How to call async methods from objective-c

Consider the below piece of code, its written in Swift and it uses Async/Await.

@objc
func sayHello(operation: String) async throws -> String {
    // some code here
    return "Tom"
}

In order to use this code in Swift, you would do this

Task {
    try await sayHello("tom")
}

This can be called from objective-c directly as follows

- (void)sayHelloWithOperation:(NSString *)operation completionHandler:(void (^)(NSString * _Nullable, NSError * _Nullable))completionHandler;

The Objective-C method implementation synthesized by the compiler will create a detached task that calls the async Swift method perform(operation:) with the given string, then (if the completion handler argument is not nil) forwards the result to the completion handler.

The synthesized Objective-C method implementation will create a detached task that calls the async throws method sayHello(operation:). If the method returns normally, the String result will be delivered to the completion handler in the first parameter and the second parameter (NSError *) will be passed nil. If the method throws, the first parameter will be passed nil (which is why it has been made _Nullable despite being non-optional in Swift) and the second parameter will receive the error. If there are non-pointer parameters, they will be passed zero-initialized memory in the non-error arguments to provide consistent behavior for callers. 

You can learn more about this here and here

Leave a Reply

Your email address will not be published. Required fields are marked *