我正在开发一个必须将命令发送到机器的应用程序。我知道如何使用委托来传播我在输入流中收到的命令的响应。但对于一些必须更新UI的命令,最好使用Callbacks。
我已经找到了一个很好的解决方案来编码,但我找不到它。
在此代码中,例如:
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!")
}
}
}
没关系,我可以使用onComplete作为回调,但是...我需要多个回调来执行多个命令:
你试过通知了吗?在您的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
}
在您的NetworkService类上
func fetchDataFromUrl(url: String) {
API.request(.GET, url)
}
func dataFetched(result: Any) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "dataFetched"), object: result)
}