【问题标题】:Add delegate to custom iOS Flutter Plugin将委托添加到自定义 iOS Flutter 插件
【发布时间】:2023-01-13 20:15:01
【问题描述】:

我正在努力将自定义 iOS 插件集成到我的 Flutter 应用程序中,问题是我没有从自定义 SDK 协议获得委托回调。

我必须将蓝牙设备连接到我的应用程序,我应该从委托调用中接收设备的 ID 并将其配对。

从 Flutter 方面,我可以从 customSdk 调用本机函数:sdkInstance.scan(),甚至有一些内部(在 sdk 内)打印扫描结果,但我的委托调用不在位。

我想我没有正确地将委托添加到 SDK,我可以让它在快速的本机应用程序中工作,但不能作为 Flutter 插件。

所以这里或多或少是代码:

iOS代码

AppDelegate.swift

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

SwiftIos插件.swift

import Flutter
import UIKit
import CustomSDK

public class SwiftIosPlugin: NSObject, FlutterPlugin {

    let sdkInstance = CustomSDK.shared // This returns an instance of the SDK
    let channel: FlutterMethodChannel


    public static func register(with registrar: FlutterPluginRegistrar) 
      let channel = FlutterMethodChannel(name: "ios_plugin_channel", binaryMessenger: registrar.messenger())
      let instance = SwiftIosPlugin(channel)

      registrar.addMethodCallDelegate(instance, channel: channel)
      registrar.addApplicationDelegate(instance)
    }

    init (_ channel: FlutterMethodChannel) {
      self.channel = channel
      super.init()
      // In Swift, this is done in viewDidLoad()
      // Is this the correct place to do this?
      sdkInstance.addDelegate(self)

    }

public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
      switch call.method {
        case "startScan":
         do {
           // This is being called and results printed
           try sdkInstance.scan()
          } catch {
            result(FlutterError(code: "400", message: "\(error)", details: nil))

          }
        case "connect":
            sdkInstance.connect(call, result)
    
        default:
          result(FlutterMethodNotImplemented)
      }
    }
}


// These should be called but are not
extension SwiftIosPlugin: CustomSDKDelegate {
    // Isn't called when scan() is executeed!
    public func onScanDevice(didScan id:String) {
        // do logic
    }

    public func onPairedDevice(didPair id:String) {
        // do logic
    }
}

【问题讨论】:

    标签: ios swift flutter appdelegate flutter-method-channel


    【解决方案1】:

    更新:

    愚蠢的事情,我希望没有其他人有这个麻烦......

    需要考虑两件事:

    • 问题是委托的某些函数public func onScanDevice(didScan id:String) 缺少参数(即使 Xcode 没有指出任何错误)。
    • sdkInstance.addDelegate(self) 在类“生命周期”中被调用得太早了。

    记住这些事情,你就不会遇到任何麻烦!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2018-09-11
      • 2016-08-12
      • 2018-11-13
      • 2021-11-11
      相关资源
      最近更新 更多