AppDelegate.swift 2.24 KB
import UIKit
import Flutter

@main
@objc class AppDelegate: FlutterAppDelegate {
    
  private var edgePanRecognizer: UIScreenEdgePanGestureRecognizer?
  private var methodChannel: FlutterMethodChannel?

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {

    // 获取 root FlutterViewController 实例
    guard let controller = window?.rootViewController as? FlutterViewController else {
      fatalError("rootViewController is not a FlutterViewController")
    }

    // 注册插件
    GeneratedPluginRegistrant.register(with: self)

    // 创建 MethodChannel,用于与 Flutter 通信
    methodChannel = FlutterMethodChannel(
      name: "ios_edge_swipe",
      binaryMessenger: controller.binaryMessenger
    )

    methodChannel?.setMethodCallHandler { [weak self] (call, result) in
      if call.method == "initSwipeListener" {
        self?.setupEdgeSwipeGesture(controller: controller)
        result(nil)
      }
    }

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  // 添加边缘滑动手势识别器
  private func setupEdgeSwipeGesture(controller: UIViewController) {
    if edgePanRecognizer != nil {
        return // 防止重复添加
    }

    edgePanRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleEdgeSwipe(_:)))
    edgePanRecognizer?.edges = [.left] // 监听左边缘
    edgePanRecognizer?.delegate = self

    controller.view.addGestureRecognizer(edgePanRecognizer!)
    print("✅ 左边缘滑动手势监听已添加")
  }

  // 触发时回调
  @objc private func handleEdgeSwipe(_ gesture: UIScreenEdgePanGestureRecognizer) {
    if gesture.state == .recognized {
      methodChannel?.invokeMethod("onEdgeSwipe", arguments: nil)
      print("👈 左边缘滑动检测到!已通知 Flutter")
    }
  }
}

// 可选:防止冲突的手势识别设置
extension AppDelegate: UIGestureRecognizerDelegate {
  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    // 如果需要同时识别,比如与 WebView 的滚动手势共存
    return true
  }
}