[英]Multiple Callbacks instead of use Delegates in swift
I am developing an app that have to send commands to a machine. 我正在开发一个必须向计算机发送命令的应用程序。 I know how to use delegates to propagate the response of the commands that I receive in an Input Stream. 我知道如何使用委托来传播在输入流中收到的命令的响应。 But probably is better to use Callbacks for some commands who have to update the UI. 但是对于某些需要更新UI的命令,最好使用Callbacks。
I have searched for a good solution to code this, but I couldn't find it. 我一直在寻找一个很好的解决方案来编写此代码,但找不到。
In this code, for example: 在此代码中,例如:
class NetworkService {
var onComplete: ((result: String)->())? //an optional function
func fetchDataFromUrl(url: String) {
API.request(.GET, url) { result in
onComplete?(result: result)
}
}
class MyViewController: UIViewController {
let networkService = NetworkService()
override func viewDidLoad() {
super.viewDidLoad()
networkService.onComplete = { result in
print("I got \(result) from the server!")
}
}
}
It's ok, I can use onComplete as a callback, but... I need multiple callbacks for multiple commands: 可以,我可以将onComplete用作回调,但是...我需要针对多个命令的多个回调:
Have you tried notifications? 您是否尝试过通知? on your ViewDidLoad: 在您的ViewDidLoad上:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(dataFetched), name: NSNotification.Name(rawValue: "dataFetched"), object: nil)
networkService.fetchDataFromUrl(url: url)
}
func dataFetched(_ notification: Notification) {
// do your stuff with notification.object
}
on your NetworkService class 在您的NetworkService类上
func fetchDataFromUrl(url: String) {
API.request(.GET, url)
}
func dataFetched(result: Any) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "dataFetched"), object: result)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.