iOS 发送消息给Flutter

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<HomePage> {
  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';
    });
  }

}

上一篇:客户端基础知识—— iOS 系统上 mmap 的“妙用”


下一篇:iOS开发之功能模块--模糊效果