在我的 Flutter App 中,我想从本机 iOS 代码(从 AppDelegate 类中的通知接收器)调用 dart 方法,并且我正在使用带有 invokeMethod 的通道来实现这一点,从 dart 端,一切都设置正确,从 iOS 端一切都是设置正确并且调用正确发生,但从未调用 dart 方法调用处理程序,并且从未收到 iOS 中的 invokeMethod 调用的回调,不知道我是否遗漏了什么,这是我双方的代码:
在斯威夫特方面:
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
}
在 Dart 方面:(在我的一个小部件类中)
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');
}
}
}