我想在ViewController中收到相同的回调函数,该函数在我的Swift应用程序中的服务器响应时打开。
我有两个ViewControllers。第一个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)
如何在两个ViewControllers上的viewDidAppear中调用该函数,以便每次在两个视图之间切换时都能获得响应?您不需要在ViewControllers之间传递networkService
。
override func viewDidAppear(_ animated: Bool) {
networkService!.onFunction = { result in
print("I got \(result) from the server!")
}
}
您可以使用通知,但在视图之间切换时必须注册和取消注册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")
}
}