Arnav
Arnav

Reputation: 1454

Flutter - How to invoke channel in native Swift code?

I have written native Swift code in my AppDelegate, I am trying to invoke a third party sdk callback in my dart side of code, however the declaration of my method channel can only be done in application function. How do I invoke a channel in my delegate methods to make a dart callback?

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

I can't declare my methodChannel outside my application as the window doesn't get recognised.

Upvotes: 1

Views: 1878

Answers (1)

Sami Haddad
Sami Haddad

Reputation: 1416

Define the method channel in the AppDelegate:

var methodChannel: FlutterMethodChannel!

Initialize it:

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

}

Now you can call invokeMethod:

public func requestDidSucceed(_ placement: TJPlacement!) {
  methodChannel.invokeMethod()
}

Upvotes: 2

Related Questions