【发布时间】:2019-04-23 21:30:00
【问题描述】:
我想在我的 Swift 应用程序中服务器响应时打开的 ViewController 中接收相同的回调。
我有两个 ViewController。第一个 ViewController 从“NetworkService”类注册一个回调。
第二个 ViewController 从第一个 ViewController 打开,第二个从变量中初始化的 firstViewController 接收“NetworkService”,然后注册相同的回调。
当我尝试从服务器接收回调时,如果第一个 ViewController 被打开,我会收到响应。如果我打开第二个 ViewController 并重新发送响应,我会在第二个 ViewController 中正确地得到它。
但是,如果我返回第一个 ViewController 并收到响应,则它始终只会在第二个 ViewController 上收到。
class NetworkService {
var onFunction: ((_ result: String)->())?
func doCall() {
self.onFunction?("result")
}
}
class MyViewController: UIViewController {
let networkService = NetworkService()
override func viewDidLoad() {
super.viewDidLoad()
networkService.onFunction = { result in
print("I got \(result) from the server!")
}
}
}
我打开 secondViewController 喜欢:
let vc = self.storyboard!.instantiateViewController(withIdentifier: "second") as! SecondViewController
vc. networkService = networkService
self.navigationController?.pushViewController(vc, animated: true)
还有第二个 ViewController:
class SecondViewController: UIViewController {
var networkService: NetworkService?
override func viewDidLoad() {
super.viewDidLoad()
networkService!.onFunction = { result in
print("I got \(result) from the server!")
}
}
}
如何在第一个 ViewController 中再次接收响应,然后从调用 popViewController 的第二个返回到第一个 ViewController?
self.navigationController?.popViewController(animated: false)
【问题讨论】:
-
你为什么不尝试
NSNotification而不是回调。这样,无论您身在何处,您都会收到该通知的所有观察者的回调。
标签: ios swift uiviewcontroller callback popviewcontroller