swift-interception

CI SwiftPM 5.9 Platforms @capturecontext

用于在 Swift 中拦截 objc selector 的包。

用法

基础

观察 NSObject 实例上的 selector

import Interception

navigationController.setInterceptionHandler(
  for: _makeMethodSelector(
    selector: UINavigationController.popViewController,
    signature: navigationController.popViewController
  )
) { result in 
  print(result.args) // `animated` flag
  print(result.output) // popped `UIViewController?`
}

如果您愿意使用宏,您也可以使用 InterceptionMacros 来简化方法 selector 的创建

import InterceptionMacros

navigationController.setInterceptionHandler(
  for: #methodSelector(UINavigationController.popViewController)
) { result in 
  print(result.args) // `animated` flag
  print(result.output) // popped `UIViewController?`
}

宏需要 swift-syntax 编译,因此会影响冷启动编译时间

您也可以设置多个拦截处理器,只需确保每个处理器使用不同的键即可

import Intercexption

object.setInterceptionHandler(
  for: _makeMethodSelector(
    selector: #selector(MyObject.someMethod(arg1:arg2)),
    signature: MyObject.someMethod(arg1:arg2)
  ),
  key: "argumentsPrinter"
) { result in 
  // In case of multiple arguments
  // you can access them as a tuple
  print(result.args.0)
  print(result.args.1)
}
import InterceptionMacros

object.setInterceptionHandler(
  for: #methodSelector(MyObject.someMethod(arg1:arg2)),
  key: "argumentsPrinter"
) { result in 
  // In case of multiple arguments
  // you can access them as a tuple
  print(result.args.0)
  print(result.args.1)
}

库开发

如果您使用它来创建库,那么隐式导出自定义 selector 可能是一个好主意

// Exports.swift
@_exported import _InterceptionCustomSelectors

您可能还会发现一些有用的 @_spi 方法和实用工具

@_spi(Internals) import Interception
import _InterceptionUtils // Is not shown in the autocomplete

有关使用示例,请参见 combine-interception

安装

基础

您可以通过将 Interception 添加为包依赖项来将其添加到 Xcode 项目中。

  1. 文件菜单中,选择Swift Packages › Add Package Dependency…
  2. 在包存储库 URL 文本字段中输入 "https://github.com/capturecontext/swift-interception.git"
  3. 选择您需要链接到项目的产品。

推荐

如果您的项目使用 SwiftPM,您可以将 CombineInterception 添加到您的包文件中。

.package(
  url: "https://github.com/capturecontext/swift-interception.git", 
  .upToNextMinor(from: "0.3.0")
)

不要忘记目标依赖项

.product(
  name: "Interception", 
  package: "swift-interception"
)
.product(
  name: "InterceptionMacros",
  package: "swift-interception"
)

许可证

此库是在 MIT 许可证下发布的。有关详细信息,请参见 LICENCE

有关灵感来源及其许可证,请参见 ACKNOWLEDGMENTS