Skip to main content

Method Types

Napacitor methods are plain C# methods marked [NapacitorMethod]. Where Capacitor distinguishes promise vs. callback vs. watch methods at the message level, Napacitor derives everything from the C# signature: single async results are Task<T> returns, and repeated callbacks are plugin events.

Supported Signatures​

The bridge supports exactly one of three parameter shapes:

ShapeC# signatureJS side
No parameterspublic Task<Result> Get()Plugin.get()
One typed DTOpublic Task<Result> Do(Options options)Plugin.do({ ... })
One NapacitorCallpublic Task<Result> Do(NapacitorCall call)Plugin.do(anything)

More than one parameter throws InvalidArguments — bundle your input into a DTO instead.

Return Values​

Methods may return void, Task, Task<T>, ValueTask, or ValueTask<T>. The bridge awaits the result and unwraps it:

  • null / void → resolves null
  • a typed value → resolves the value serialized as camelCase JSON

There is no saveCall step: an async method that completes later simply resolves the promise later.

Repeated Callbacks (watch pattern)​

For streaming data (sensor readings, position updates, battery changes), combine an event with the listener lifecycle hooks:

// JS
const handle = await MyPlugin.addListener('someEvent', (data) => { ... });
await handle.remove();
// C#
protected override void OnListenerAdded(string eventName)
{
if (eventName == "someEvent")
{
// start the native source
}
}

protected override void OnListenerRemoved(string eventName)
{
if (eventName == "someEvent")
{
// stop the native source
}
}

private void OnNativeReading(object? sender, SomeEventArgs e)
{
NotifyListeners("someEvent", new SomeData { ... });
}

An alternative for state-based APIs is a watch* method that takes a JS callback ID and calls it back repeatedly — but prefer the event pipeline; it is what the official plugins use (see the Battery plugin as the reference implementation).

Argument Deserialization​

DTOs are deserialized with NapacitorJson.Options: camelCase and case-insensitive, both directions. If the payload cannot be deserialized, the call rejects with InvalidArguments and a descriptive message. Unknown properties are ignored by default.

NapacitorCall gives you the raw JsonElement:

using Napacitor.Plugins;

[NapacitorMethod]
public Task<object?> Do(NapacitorCall call)
{
var args = call.Args; // JsonElement of the full argument payload
var value = call.Get<string>("value"); // convenience accessor
return Task.FromResult<object?>(value);
}

See Data Types for serialization details.

Errors​

Throw NapacitorException with a code to reject the JS promise:

throw new NapacitorException(NapacitorException.Unavailable, "Requires iOS 18+");
throw NotImplemented("doSomething"); // NOT_IMPLEMENTED

See C# Plugin Guide for the code list.