iOS 发送消息给Flutter

iOS 发送消息给Flutter,第1张

iOS 发送消息代码


lazy var messageChannel:FlutterBasicMessageChannel  = {
        let navigation = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController
        guard let contoller = navigation?.viewControllers.first as? FlutterViewController else {
            fatalError("contoller is not type FlutterViewController")
        }
        
        let channel = FlutterBasicMessageChannel(name: "NativeToFlutterMesseage", binaryMessenger: contoller.binaryMessenger,codec: FlutterJSONMessageCodec.sharedInstance());
        return channel
    }()


override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
                
        
        let sendBtn = UIButton(type: .custom)
        sendBtn.frame = CGRect(x: 0, y: 0, width: 120, height: 50)
        sendBtn.setTitle("发送消息", for: .normal)
        sendBtn.setTitleColor(.blue, for: .normal)
        view.addSubview(sendBtn)
        sendBtn.center = view.center
        sendBtn.addTarget(self, action: #selector(sendMsgEvent), for: .touchUpInside)
        
        // Do any additional setup after loading the view.
    }

@objc func sendMsgEvent() {
        messageChannel.sendMessage(["name":"Mark","birthday": 10])
    }

flutter 接收消息代码

class _HomePageState extends State {
  static const messageChannel =
      BasicMessageChannel("NativeToFlutterMesseage", JSONMessageCodec());

  @override
  void initState() {
    super.initState();
    receiveMessage();
  }

  void receiveMessage() {
    messageChannel.setMessageHandler((message) async {
      print('received message = $message');
      return 'Reply from Dart';
    });
  }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/996853.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存