Custom Capacitor Plugins and Swift Delegate

I’m writing a small plugin that wraps around a 3rd party device that uses Bluetooth using Swift delegates.
This means that when I fire a method (let’s say readBatteryStatus) the method doesn’t return any value, but instead a second method called (batteryStatusRecived) is fired when the operation is done.

Is there a best practice for handling this? I’ve seen some examples on how to wrap the delegate inside a promise (https://github.com/mxcl/PromiseKit/issues/136#issuecomment-72279182 for example) but they are considered somewhat hacky (according to the writer, I’m not a Swift expert).

Thanks

In a way PluginCall is a sort of promise, so you could store it on a register handler of some sort, and then when these Bluetooth delegate methods are called , you could call call.reject or call.resolve.

The Geolocation plugin follows this format (it’s using the older success and error methods which are just aliases for resolve and reject): https://github.com/ionic-team/capacitor/blob/249073d6edae594e6cf324cacbce9347fdaa4b53/ios/Capacitor/Capacitor/Plugins/Geolocation.swift#L54

And where the call is first saved and registered: https://github.com/ionic-team/capacitor/blob/249073d6edae594e6cf324cacbce9347fdaa4b53/ios/Capacitor/Capacitor/Plugins/Geolocation.swift#L95

Does that help at all or am I not understanding the question?

1 Like

I believe it does - thanks