X09
X09

Reputation: 3956

How to override iOS App lifecycle in Flutter plugin

On the Swift end of my flutter plugin, I needed to override applicationDidBecomeActive and applicationWillResignActive but I don't know how to go about this.

Assuming it is just a plain flutter app, I would have done this in AppDelegate:

   override func applicationDidBecomeActive(_ application: UIApplication) {
        
    }
    
    override func applicationWillResignActive(_ application: UIApplication) {
        
    }

But that doesn't appear to be working on the plugin class.

Please, note that I am aware that I can do this using AppLifecycleState on the Flutter end, but like I said it is important that I do this on the Swift end

Upvotes: 2

Views: 2568

Answers (1)

Rafael Setragni
Rafael Setragni

Reputation: 170

You need to implement the FlutterApplicationLifeCycleDelegate interface and register it using register method on your FlutterPlugin class.

OBS: FlutterPlugin class has already inherinted FlutterApplicationLifeCycleDelegate interface, so you don't need to worry about it

Step 1: register your pluggin as an ApplicationDelegate class:

public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "my_wonderful_plugin_id", binaryMessenger: registrar.messenger())
    let instance = MyWonderfulPlugin() // YOUR PLUGGIN NAME INSTEAD

    registrar.addMethodCallDelegate(instance, channel: channel)
    registrar.addApplicationDelegate(instance) // THIS IS THE BIG SECRET
}

Step 2: Implement the interface, including the methods bellow on your plugin class:

public func applicationDidBecomeActive(_ application: UIApplication) {
    debugPrint("applicationDidBecomeActive")
}

public func applicationWillTerminate(_ application: UIApplication) {
    debugPrint("applicationWillTerminate")
}

public func applicationWillResignActive(_ application: UIApplication) {
    debugPrint("applicationWillResignActive")
}

public func applicationDidEnterBackground(_ application: UIApplication) {
    debugPrint("applicationDidEnterBackground")
}

public func applicationWillEnterForeground(_ application: UIApplication) {
    print("applicationWillEnterForeground")
}

Thats it! Yahoooow!

Upvotes: 7

Related Questions