简体   繁体   English

How to call a swift view controller using the navigation controller in flutter through the Flutter Method Channel

[英]How to call a swift view controller using the navigation controller in flutter through the Flutter Method Channel

I am trying to call a UINavigationController I have defined in a separate file called "MainNavigationController.swift" through a private function I have defined in my AppDelegate.swift file called "callNavigator()" I am calling that method from the Flutter side through a method channel that is successfully sending back a message that some communication is happening "There is no problem on the Flutter/Dart side". I am trying to call a UINavigationController I have defined in a separate file called "MainNavigationController.swift" through a private function I have defined in my AppDelegate.swift file called "callNavigator()" I am calling that method from the Flutter side through a成功发回消息的方法通道正在发生一些通信“Flutter/Dart 端没有问题”。 I want the function to push a view on top of the flutter screen using the navigator defined in "MainNavigationController.swift".The code in my MainNavigationController.swift is as follows:我希望 function 使用“MainNavigationController.swift”中定义的导航器在 flutter 屏幕上推送视图。我的 MainNavigationController.Z818056DBD7E201241206B9C7CD884 中的代码如下:

import Foundation
    import UIKit

    class MainNavigationController: UINavigationController{
        override func viewDidLoad() {
            super.viewDidLoad()
        }
        private func navigateToMainInterface() {
            let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
           guard let mainNavigationVc = mainStoryboard.instantiateViewController(withIdentifier:"MainNavigationController") as? MainNavigationController else {
                return

            }
            present(mainNavigationVc, animated: true, completion: nil)

        }
    }
Then I am trying to call this class in my "AppDelegate.swift file" through my "callNavigator()" private function as a constructor. The code is as follows in the Appdelegate.swift file :


    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?

      ) -> Bool {
        let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
        GeneratedPluginRegistrant.register(with: self)      

        let navigatorChannel = FlutterMethodChannel(name: "com.fluttertonative/navigateToCameraSDK", binaryMessenger:  controller.binaryMessenger)
       navigatorChannel.setMethodCallHandler ({
          [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
          // Note: this method is invoked on the UI thread.
          guard call.method == "getSwiftNavigator" else {
            result(FlutterMethodNotImplemented)
            return
          }
          self?.callNavigator()

       })
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
        private func receiveGreeting(result: FlutterResult){
            result("Hello from Swift Code...")
        }
        private func callNavigator(){
            MainNavigationController()

        }
    }

However, I am getting a warning in Xcode that the "callNavigator" function trying to call "MainNavigationController" is not using its result it's saying "Result of 'UINavigationController' initializer is unused".但是,我在 Xcode 中收到警告,试图调用“MainNavigationController”的“callNavigator”function 没有使用其结果,它说“'UINavigationController' 初始化程序的结果未使用”。 I am new to swift and I am not sure what to do.我是 swift 的新手,我不知道该怎么做。

I have set the Initial navigator to the FlutterViewController in my Main.storyBoard where I have placed some dummy text filed.我在我的 Main.storyBoard 中将 Initial navigator 设置为 FlutterViewController,我在其中放置了一些虚拟文本文件。 I want when I call the method channel from the Flutter side the "callNavigator" function to be run which in turn calls the " MainNavigationController" in the " MainNavigationController.swift" file, which should push a new view on top of the view in the Flutter screen.当我从 Flutter 端调用方法通道时,我希望运行“callNavigator” function ,然后调用“MainNavigationController.swift”文件中的“MainNavigationController”,它应该在视图顶部推送一个新视图Flutter屏。

I need some help achieving this as I am new to the Swift Language我需要一些帮助来实现这一点,因为我是 Swift 语言的新手

then my dart code is as follows:那么我的dart代码如下:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const navigateToCameraSDK = const MethodChannel('com.fluttertonative/navigateToCameraSDK');

  String _greeting = 'awaiting swift call..';


  Future _getnavigator() async{
    try {
      final result = navigateToCameraSDK.invokeMapMethod('getSwiftNavigator');
      print(result);
    } on PlatformException catch (e){
      print('error:$e');
      _greeting = 'error occured:$e';
    }
    setState(() {
      _greeting ='call successful you have got the swift Navigator';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(_greeting),
              CupertinoButton(
                child: Text('call swift to get the navigator'),
                onPressed: _getnavigator,
                borderRadius:BorderRadius.all(Radius.circular(13.0)),
                color: Colors.blue[300],
              ),
            ],
          ),
        ));
  }
}

and my storyboard is as follows-the Flutter View Controller is the initial View Controller.而我的storyboard如下——Flutter视图Controller是初始视图Z9BBF373797BF7CF7BA62C800236。 enter image description here:在此处输入图像描述: 在此处输入图像描述

By default, the Flutter iOS application does not have a UINavigationViewController .默认情况下,Flutter iOS 应用程序没有UINavigationViewController This is required in order to push view controllers on to the navigation stack.这是将视图控制器推送到导航堆栈所必需的。

It's quite easy to add this through the AppDelegate class though.不过,通过AppDelegate class 添加它非常容易。


import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
    var navigationController: UINavigationController!
    
    override func application(_ application: UIApplication,
                            didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      
      
        let controller = window?.rootViewController as! FlutterViewController
        GeneratedPluginRegistrant.register(with: self)
        
        // create and then add a new UINavigationController
        self.navigationController = UINavigationController(rootViewController: controller)
        self.window.rootViewController = self.navigationController
        self.navigationController.setNavigationBarHidden(true, animated: false)
        self.window.makeKeyAndVisible()
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

}

Later on when you add a FlutterMethodChannel to your app delegate, you can simple push/show a new UIViewController in the standard iOS way.稍后,当您将FlutterMethodChannel添加到您的应用程序委托时,您可以以标准 iOS 方式简单地推送/显示新的UIViewController

    // called from within the FlutterMethodChannel handler
    private func pushViewController() {
        //get view controller from StoryBoard, XIB or in code
        let vc = ...       
        self.navigationController.setNavigationBarHidden(false, animated: true)
        self.navigationController.pushViewController(vc, animated: true)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM