我正在将一个自定义iOS插件集成到我的Flutter应用程序中,问题是我没有从自定义SDK协议中获得委托回调。
我必须将蓝牙设备连接到我的应用程序,我从代表呼叫中接收设备的ID并配对。
在Flutter端,我可以从customSdk调用本地函数:sdkInstance.scan()
,甚至有一些内部(在sdk内部)打印扫描结果,但我的委托调用没有到位。
我想我没有正确地将委托添加到SDK中,我可以让它在swift原生应用中工作,但不能作为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)
}
}
SwiftIosPlugin.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
}
}
1条答案
按热度按时间a11xaf1n1#
更新:
愚蠢的是,我希望没有其他人有这个麻烦...
需要考虑两件事:
public func onScanDevice(didScan id:String)
缺少参数(即使Xcode没有指出任何错误)。sdkInstance.addDelegate(self)
在类"生命周期"中调用得太早。注意这些事情,你就不会有任何麻烦了!