打开一个视图控制器时如何在两个视图控制器中接收相同的回调?

How to receive same callback in two ViewControllers when one is opened?

我想在我的 Swift 应用程序中服务器响应时打开的 ViewController 中接收相同的回调。

我有两个 ViewController。第一个 ViewController 从 class "NetworkService".

注册回调

第二个ViewController从第一个ViewController打开,第二个从第一个ViewController接收"NetworkService"初始化在一个变量中,然后注册相同打回来。

当我尝试从服务器接收回调时,如果第一个 ViewController 打开,我会收到响应。如果我打开第二个 ViewController 并重新发送响应,我会在第二个 ViewController 中正确地得到它。

但是如果我 return 到第一个 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!")
        }

    }
}

我打开第二个ViewController喜欢:

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 return 到第一个 ViewController?

self.navigationController?.popViewController(animated: false)  

如何在两个 ViewController 上调用 viewDidAppear 中的函数,以便每次在两个视图之间切换时都能得到响应?您不需要在 ViewController 之间传递 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")
    }
}