我想在我的Swift应用程序中服务器响应时打开的ViewController中收到相同的回调。
我有两个ViewController。第一个ViewController从“ NetworkService”类注册一个CallBack。
第二个ViewController从第一个ViewController打开,第二个ViewController从firstViewController接收初始化为变量的“ NetworkService”,然后注册相同的callBack。
当我尝试从服务器接收回调时,如果打开了第一个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)
答案 0 :(得分:0)
如何在两个ViewController上的viewDidAppear中调用该函数,以便每次在两个视图之间切换时都能得到响应?您无需在ViewController之间传递networkService
。
override func viewDidAppear(_ animated: Bool) {
networkService!.onFunction = { result in
print("I got \(result) from the server!")
}
}
答案 1 :(得分:0)
您可以使用通知,但是在视图之间切换时必须注册和注销VC。另一个选择是使用委托,您将需要共享NetworkService实例。这是如何与协议一起工作的快速示例。
protocol NetworkServiceProtocol {
var service: NetworkService? { get }
func onFunction(_ result: String)
}
class NetworkService {
var delegate: NetworkServiceProtocol?
func doCall() {
self.delegate?.onFunction("results")
}
func update(delegate: NetworkServiceProtocol) {
self.delegate = delegate
}
}
class VC1: UIViewController, NetworkServiceProtocol {
var service: NetworkService?
init(service: NetworkService? = nil) {
self.service = service
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.service?.update(delegate: self)
}
func onFunction(_ result: String) {
print("On Function")
}
}