1

我已经在我的 Swift 中编写了本机 Swift 代码AppDelegate,我试图在我的 dart 代码端调用第三方 sdk 回调,但是我的方法通道的声明只能在application函数中完成。如何在委托方法中调用通道来进行 dart 回调?

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, TJPlacementDelegate {
    
    public func requestDidSucceed(_ placement: TJPlacement!) {
       //Need to invoke methodChannel here
    }
    public func requestDidFail(_ placement: TJPlacement!, error: Error!) {
      //Need to invoke methodChannel here
    }
    public func contentIsReady(_ placement: TJPlacement!) {
      //Need to invoke methodChannel here
    }
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        
        let channelName = "ios_native"
        let rootViewController : FlutterViewController = window?.rootViewController as! FlutterViewController
        let methodChannel = FlutterMethodChannel(name: channelName, binaryMessenger: rootViewController as! FlutterBinaryMessenger)
        
        methodChannel.setMethodCallHandler {(call: FlutterMethodCall, result: FlutterResult) -> Void in
            switch(call.method) {
            case "setDebugEnabled":
                let isDebug = call.arguments as! Bool
                Tapjoy.setDebugEnabled(isDebug)
                break;
            default: result(FlutterMethodNotImplemented)
            }
        }
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
        
    }
     
}

我不能methodChannel在我的应用程序之外声明我的应用程序,因为window它没有被识别。

4

1 回答 1

2

在 AppDelegate 中定义方法通道:

var methodChannel: FlutterMethodChannel!

初始化它:

override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
  ...
    
  methodChannel = FlutterMethodChannel(name: channelName, binaryMessenger: rootViewController as! FlutterBinaryMessenger)

}

现在你可以调用invokeMethod:

public func requestDidSucceed(_ placement: TJPlacement!) {
  methodChannel.invokeMethod()
}
于 2020-06-30T12:32:52.517 回答