允许组件之间进行发布-订阅式通信,而无需组件明确地了解彼此
pod 'SwiftEventBus', :tag => '5.1.0', :git => 'https://github.com/cesarferreira/SwiftEventBus.git'
github "cesarferreira/SwiftEventBus" == 5.1.0
5.+
适用于 swift 5
3.+
适用于 swift 4.2
2.+
适用于 swift 3
1.1.0
适用于 swift 2.2
订阅者实现事件处理方法,这些方法将在收到事件时被调用。
SwiftEventBus.onMainThread(target, name: "someEventName") { result in
// UI thread
}
// or
SwiftEventBus.onBackgroundThread(target, name:"someEventName") { result in
// API Access
}
从代码的任何部分发布事件。所有与事件类型匹配的订阅者都将收到它。
SwiftEventBus.post("someEventName")
--
发布事件
SwiftEventBus.post("personFetchEvent", sender: Person(name:"john doe"))
期望参数
SwiftEventBus.onMainThread(target, name:"personFetchEvent") { result in
let person : Person = result.object as Person
println(person.name) // will output "john doe"
}
引用Apple官方文档
常规通知中心在发布通知的线程中传递通知
关于此限制,@nunogoncalves 实现了该功能并提供了可用的示例
@IBAction func clicked(sender: AnyObject) {
count++
SwiftEventBus.post("doStuffOnBackground")
}
@IBOutlet weak var textField: UITextField!
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
SwiftEventBus.onBackgroundThread(self, name: "doStuffOnBackground") { notification in
println("doing stuff in background thread")
SwiftEventBus.postToMainThread("updateText")
}
SwiftEventBus.onMainThread(self, name: "updateText") { notification in
self.textField.text = "\(self.count)"
}
}
//Perhaps on viewDidDisappear depending on your needs
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
SwiftEventBus.unregister(self)
}
--
从目标中删除所有观察者
SwiftEventBus.unregister(target)
从目标中删除具有相同名称的观察者
SwiftEventBus.unregister(target, "someEventName")