Search code examples
c#ios.netxamarinjavascriptcore

Xamarin IOS Cant Bind function or callback In JavascriptCore


Following the example here: JSContext

I receive the following exception:

{TypeError: myCSharpObject.myFunc is not a function. (In 'myCSharpObject.myFunc()', 'myCSharpObject.myFunc' is undefined)} 

My code is as follows:

        JSContext _context;
        _context = new JSContext();

        var jsCallback = new MyJSExporter();

        _context[(NSString)"myCSharpObject"] = JSValue.From(jsCallback, _context);

        var result = _context.EvaluateScript("myCSharpObject.myFunc();");

With the protocol defined as:

[Protocol]
    interface IMyJSVisibleProtocol : IJSExport
    {
        [Export("myFunc")]
        int MyFunc();

        [Export("Arity2:With:")]
        NSObject Arity2With(NSObject arg1, NSObject arg2);
    }

    class MyJSExporter : NSObject, IMyJSVisibleProtocol
    {
        public int MyFunc()
        {
            Console.WriteLine("Called!");
            return 42;
        }

        public NSObject Arity2With(NSObject arg1, NSObject arg2)
        {
            Console.WriteLine("Arity 2 function called with " + arg1 + " " + arg2);
            return (NSNumber)42;
        }
    }

And the exception handler as:

       _context.ExceptionHandler = (context, exception) => {
            // {TypeError: myCSharpObject.myFunc is not a function. (In 'myCSharpObject.myFunc()', 'myCSharpObject.myFunc' is undefined)}
        };

Solution

  • What finally fixed this for me was adding the build mtouch argument:

    '--registrar:static'

    enter image description here