Calling Dart code from native iOS is not working using invokeMethod

688 views Asked by At

In my Flutter App, I want to call dart method from native iOS code (from notification receiver in AppDelegate class), and I'm using channel with invokeMethod to achieve so, from dart side, everything is set correctly and from iOS side everything is set correctly and the call is happening correctly but the dart method call handler is never called and the callback of invokeMethod call in iOS is never received, don't know if I'm missing something, here is my code in both sides:

in Swift side:

var channel = FlutterMethodChannel()

// channel is created when registering app plugins
func registerPlugins(with registry: FlutterPluginRegistry) {
    
    let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
    let redViewController = mainStoryBoard.instantiateViewController(withIdentifier: "AppIdentifier") as! FlutterViewController
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = redViewController
     
    let controller : FlutterViewController = self.window.rootViewController as! FlutterViewController;
    self.channel = FlutterMethodChannel(name: "myApp.main/backgroundNotifications",
                                                      binaryMessenger: 
    controller.binaryMessenger);
}


// the background notification receiver
override func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void){

  // comes here    
  DispatchQueue.main.async {
      self.channel.invokeMethod("toTo", arguments: userInfo, result: {(r:Any?) -> () in
          print(r.debugDescription);  // Never comes here
      })
  }
  // comes here with no errors of execution to previous call

}

in Dart side: (in one of my widgets classes)

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {

  MethodChannel _channel =
  const MethodChannel('myApp.main/backgroundNotifications');

  @override
  void initState() {
    super.initState();
    .
    .
    .
    _channel.setMethodCallHandler(toTo);
  }

  Future<dynamic> toTo(MethodCall call) async {
    print("init state setMethodCallHandler ${call.method}"); // Never comes here
    switch (call.method) {
      case 'toTo':
        return 145.0;
      case 'bar':
        return 123.0;
      default:
        throw MissingPluginException('notImplemented');
    }
  }

}
0

There are 0 answers