How to receive the app delegate calls in a Swift Flutter plugin?

Viewed 2183

I am writing a Flutter plugin in Swift. I have successfully created the plugin and can call my Swift functions from Flutter using the default code that is generated when you create a new Flutter plugin. My Swift code currently looks like this.

public class MyFlutterPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "my_plugin", binaryMessenger: registrar.messenger())
    let instance = MyFlutterPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    if call.method == "hello" {
      result("hello from swift")
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}

I would like app delegate calls (for example when a notification is received) to be sent to my plugin. I would like to know how to make this work with Swift.

I have seen in the source code from some Objective C plugins the line [registrar addApplicationDelegate:instance];. But I don't know how to achieve anything like this in Swift and the official documentation doesn't seem to exist for this.

1 Answers

It turns out it is fairly simple. Use registrar.addApplicationDelegate(instance) to register to receive the calls. Then include app delegate methods like this:

public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }
    let token = tokenParts.joined()
    channel.invokeMethod("onToken", arguments: token)
}
Related