2

I am trying to write an iOS plugin for Unity, which requires the use of a bridge with a C layer.

The plugin itself is written in Swift.

Currently my implementation works like so:

// Swift

@objc public class SomeClass {
 @objc public func SomeFunction() -> String {
 return "Hello"
 }
}

// C

extern "C" {
 void _someFunction() {
 // I can access the Swift file using "[SomeClass shared]"
 // This returns the "Hello" string correctly
 NSString *helloMessage = [[SomeClass shared] SomeFunction];
 }
}

This works, but now I need to make an async call which requires a callback from the Swift implementation.

// Swift

@objc public class SomeClass {
 @objc public func SomeFunction(completionHandler: (String) -> Void) {
 // Gets called after some async operations
 completionHandler("hello")
 }
}

Is it possible to call this Swift function from the C layer and how would you do so?

// C

extern "C" {
 void _someFunction() {
 // ??????
 }
}
asked Feb 4, 2022 at 11:42

1 Answer 1

1

If you set up bridging well then the call should be like

void _someFunction() {
 [[SomeClass shared] SomeFunctionWithCompletionHandler:^(NSString * _Nonnull value) {
 NSLog(@"Result: %@", value);
 }];
}

Btw, classes to be visible in Objective-C should be 'is-a' NSObject, like

@objcMembers public class SomeClass: NSObject {
 public static var shared = SomeClass()
 public func SomeFunction() -> String {
 return "Hello"
 }
 public func SomeFunction(completionHandler: (String) -> Void) {
 // Gets called after some async operations
 completionHandler("hello")
 }
}

Tested with Xcode 13.2 / iOS 15.2

answered Feb 6, 2022 at 4:55
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for replying! I have tried this implementation, but it throws an error "No visible @interface for ’SomeClass’ declares the selector ‘SomeFunction:’". Even though it could find the function I had previously without the 'completionHandler'.
Never mind, I didn't write the 'WithCompletionHandler' part. Best use the Xcode autocomplete!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.