【问题标题】:How to receive the app delegate calls in a Swift Flutter plugin?如何在 Swift Flutter 插件中接收应用程序委托调用?
【发布时间】:2020-05-24 16:55:31
【问题描述】:

我正在用 Swift 编写一个 Flutter 插件。我已经成功创建了插件,并且可以使用创建新 Flutter 插件时生成的默认代码从 Flutter 调用我的 Swift 函数。我的 Swift 代码目前看起来像这样。

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)
    }
  }
}

我希望将应用委托调用(例如收到通知时)发送到我的插件。我想知道如何使用 Swift 进行这项工作。

我在一些 Objective C 插件的源代码中看到了 [registrar addApplicationDelegate:instance]; 这一行。但我不知道如何在 Swift 中实现这样的目标,而且官方文档似乎也不存在。

【问题讨论】:

    标签: ios swift flutter


    【解决方案1】:

    事实证明它相当简单。使用registrar.addApplicationDelegate(instance) 注册接听电话。然后包括这样的应用委托方法:

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多