用于在 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 项目中。
"https://github.com/capturecontext/swift-interception.git"
如果您的项目使用 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。