当前位置:   article > 正文

swift 与flutter通信实现_flutter暴露方法给swift

flutter暴露方法给swift

swift 代码为

//
//  ViewController.swift
//  IOS_to_Flutter
//
//  Created by log on 2021/1/20.
//

import UIKit
import Flutter
 

class ViewController: UIViewController,FlutterStreamHandler {
    
    //初始化的方法
    var channel:FlutterEventChannel?
    var eventSink:FlutterEventSink?
    var flutterViewController:FlutterViewController? = nil
    
    
    //ios 主动给flutter 发送消息回调方法
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events
        return nil
    }
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        return nil
    }
    
    lazy var flutterEngine:FlutterEngine = FlutterEngine(name: "my flutter engine")
    override func viewDidLoad() {
        super.viewDidLoad()
        //初始化信息
        flutterEngine.run()
        flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
        self.channel = FlutterEventChannel(name: "com.pages.flutter", binaryMessenger: flutterViewController as! FlutterBinaryMessenger)
        
        self.channel?.setStreamHandler(self)
        // Do any additional setup after loading the view.
    }

    @IBAction func clikc(_ sender: Any) {
        
        //接受flutter 发来的消息
        let  method = FlutterMethodChannel(name: "com.pages.flutter", binaryMessenger: flutterViewController as! FlutterBinaryMessenger)
        method.setMethodCallHandler { (callBack:FlutterMethodCall,  result:FlutterResult) -> Void in
        //获取flutter 返回的信息
            print(callBack.method,callBack.arguments ?? "")
            if callBack.method == "method_native_result_callback" {
                //被动发送消息回传给flutter
                    result("flutter: hello")
            }
        }

        //swift 发送信息给flutter
        let dic:[String:String] = ["hello":"flutter"];
        self.eventSink?(dic)
       
        self.present(flutterViewController!, animated: true, completion: nil)
        
    }
  
    
}



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

flutter 代码为

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();

}

class _MyHomePageState extends State<MyHomePage> {
  String _content="234";

  //flutter 发送消息给swift的方法通道
  static const methodChannel = const MethodChannel("com.pages.flutter");
  flutter 接收swift 信息的通道
  static const EventChannel eventChannel = const EventChannel('com.pages.flutter');//App/Event/Channel和iOS的一致
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //开始监听,swfit 发来的的消息
    eventChannel
        .receiveBroadcastStream("init")
        .listen(_onEvent, onError: _onError);
  }
  // 数据接收
  void _onEvent(Object value) {
    print('fuck me+$value');
    setState(() {
      _content = value.toString();

    });
  }

// 错误处理
  void _onError(dynamic) {}

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
                onPressed: (){
                  //flutter 发送消息的方法
                  methodChannel.invokeMethod("method_no_params",null);
                },
              child: Text('no params'),
            ),
            RaisedButton(
              child: Text('params'),
                onPressed: (){
                  Map<String,String> parms = {"params":"hello swift"};
                  methodChannel.invokeMapMethod("method_params",parms);
                }
            ),
            RaisedButton(
              child: Text("native callback"),
                onPressed: (){
                  _nativeCallBackWithparams();
                }
            ),
            Text(_content != null ? _content : "kong",style: TextStyle(color: Colors.green),)
          ],
        ),
      ),
    );
  }

  Future<Null> _nativeCallBackWithparams() async {
    String result ;
    try{
      result = await methodChannel.invokeMethod("method_native_result_callback",null);
    } on PlatformException catch (e) {
      result = "failed to get params:'${e.message}'";
    }
    setState(() {
      _content = result;
    });
  }


}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/383221
推荐阅读
相关标签
  

闽ICP备14008679号