Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

Capacitor and the Ionic Native Shake Plugin


In a client application (Android and iOS) I recently needed the shake gesture. Fortunately, there is an Ionic Native plugin for this. Although only iOS support appears in the documentation, the plugin worked without any problems under Cordova / Capacitor on Android. There were also no problems with the combination of Cordova and iOS. But the combination of Capacitor and iOS did not work. Since the app was already developed with Capacitor and I did not want to give away the advantages of Capacitor, I did some research. And it was easy to find out why it didn’t work. I tried to implement the motionEnded method (which notifies the Shake Plugin) in the CDVViewController.m file because there was no MainViewController.m anymore. That did not work but I luckily remembered that Capacitor 2 uses Swift instead of Objective C. So I only need to override the motionEnded method in CAPBridgeViewController.swift.

The Objective C version:

- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent*)event {
  if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CDVShakeDeviceShaken" object:self];

The Swift variant:

override public func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
  if motion == .motionShake { Notification.Name("CDVShakeDeviceShaken"), object: self)

Yeah…shake it, baby.