Flutter iOS 与 flutter 相互通信升级

Flutter iOS 与 flutter 相互通信升级

iOS端代码:

bash 复制代码
import Foundation
import flutter_boost


class HYFlutterCommonChannel: NSObject {
    
    @objc public static let share = HYFlutterCommonChannel()
    
    var channel: FlutterMethodChannel
    
    lazy var map: [String:(_ call: FlutterMethodCall, _ result:@escaping FlutterResult) -> Void] = {
        return [
            "notifyNativeEventResult":notifyNativeEventResult,
            "getISBuildRelease":getISBuildRelease,
        ]
    }()
    
    override init() {
        channel = FlutterMethodChannel.init(name: "Flutter/common", binaryMessenger: FlutterBoost.instance().engine().binaryMessenger)
        super.init()
        // 注册 flutter 回调原生方法
        channel.setMethodCallHandler {[weak self] (call, result) in
            let method = self?.map[call.method]
            method?(call, result)
        }
    }
    
    @objc public static func start() {
        _ = HYFlutterCommonChannel.share
    }
    
    // 获取版型状态
    func getISBuildRelease(call: FlutterMethodCall, result:@escaping FlutterResult) {
        result(false)
    }
    
    func notifyNativeEventResult(call: FlutterMethodCall, result:@escaping FlutterResult) {
        guard let arguments = call.arguments as? [String:AnyObject],
                let type = arguments["type"] as? String else {
            return
        }
        
        switch type {
        case "selectCountryAreaCode":
            do{
//                if code = {(code: String?) in
//                    if let _code = code {
//                        self.channel.invokeMethod("onCountryAreaCodeResult", arguments: _code)
//                    }
//                }
                
                if let tabBarVC = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController,
                   let naVC = tabBarVC.selectedViewController as? UINavigationController {
                    
                    let vc = HYAreaCodeController()
                    vc.complete = {(code: String?) in
                        if let _code = code {
                            self.channel.invokeMethod("onCountryAreaCodeResult", arguments: _code)
                        }
                    }
                    naVC.navigationController?.pushViewController(vc as UIViewController, animated: true)
                }
            }
            
            break
            
        default:
            break
        }
        
        
    }
}

原生 控制器代码

bash 复制代码
class HYAreaCodeController: UIViewController {
    
    
    public var complete: ((_ code: String?)->())?
    
    lazy var codeBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.red
        btn.addTarget(self, action: #selector(codeBtnClick(_:)), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.codeBtn.frame = CGRect.init(x: 100, y: 100, width: 100, height: 40)
        self.view.addSubview(self.codeBtn)
    }
    
    
    @objc func codeBtnClick(_ sender: UIButton) {
        
        if let callback = self.complete {
            callback("将选中数据返回给Flutter")
        }
    }
    
}

到此原生使用完毕

Flutter代码

bash 复制代码
import 'dart:collection';

import 'package:flutter/services.dart';
import 'navigation_channel.dart';

class CommonChannel {
  CommonChannel() {
    init();
  }

  // ignore: constant_identifier_names
  static const MethodChannel channel_common = MethodChannel("Flutter/common");

  // ignore: non_constant_identifier_names
  static final channel_handlers = HashMap<String, MethodCallHandler>();

  void init() {
    channel_common.setMethodCallHandler((call) async {
      channel_handlers[call.method]?.call(call);
    });
  }

  void registerMethodCallHandler(String method, MethodCallHandler handler) {
    channel_handlers[method] = handler;
  }

// 获取版本状态 true -> Release
  Future<bool?> getISBuildRelease() async {
    return channel_common.invokeMethod("getISBuildRelease");
  }

  /// 打开 code 界面
  void selectAreaCode() {
    notifyNativeEventResult("selectCountryAreaCode", {});
  }

//
  void notifyNativeEventResult(String eventType, Map arguments) {
    // 第一个参数表示 method,方法名称,原生端会解析此参数
    // 第二个参数,类型任意使用Map
    // 返回 Future, 原生端返回的数据
    channel_common.invokeMethod(
        "notifyNativeEventResult", {"type": eventType, "arguments": arguments});
  }

  Future<T?> notifyNativeEventResultT<T>(String eventType, Map arguments) {
    return channel_common.invokeMethod<T?>(
        "notifyNativeEventResult", {"type": eventType, "arguments": arguments});
  }

// 注册 监听回调
// 原生会将数据返回过来,直接取 argumets即可
  void registerOnCountryAreaCodeResultHandler(MethodCallHandler? handler) {
    channel_handlers["onCountryAreaCodeResult"] = handler;
  }
}

Flutter使用

bash 复制代码
 // 使用 NavigationChannel
Channels.common.selectAreaCode();
相关推荐
Patrick_Wilson10 小时前
iOS Safari Clipboard API 权限弹窗问题
前端·ios·safari
_瑞13 小时前
APM_符号化原理
ios·汇编语言
花椒技术14 小时前
不是跑通一次 Demo:花椒 QA 怎样把真机 UI 自动化做成回归流程
ios·单元测试·测试
2501_9159184117 小时前
Swift IDE 有哪些?按平台和需求选择Swift 开发工具
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
songgeb19 小时前
UITableView 局部刷新 Crash:Invalid update
ios·架构
2501_9160074721 小时前
免费抓包工具 Windows 和 Mac 怎么选?根据平台来选择工具
网络协议·计算机网络·网络安全·ios·adb·https·udp
恋猫de小郭21 小时前
Flutter 多窗口支持类型和 API 介绍
android·前端·flutter
张风捷特烈21 小时前
当 AI 遇见 Flutter | 打造 500+ Widget 专属Logo
android·前端·flutter
念何架构之路21 小时前
响应渲染 render(render/ 包)
ios·iphone·xcode
kayyoo1 天前
Flutter的第一个Demo和Bug
flutter