gpt4 book ai didi

ios - 当两个 ViewController 打开时,如何在两个 ViewController 中接收相同的回调?

转载 作者:行者123 更新时间:2023-11-29 05:49:34 25 4
gpt4 key购买 nike

我希望在 ViewController 中收到与我的 Swift 应用程序中服务器响应时打开的相同的回调。

我有两个 ViewController。第一个 ViewController 从“NetworkService”类注册回调。

第二个 ViewController 从第一个 ViewController 打开,第二个 ViewController 从变量中初始化的第一个 ViewController 接收“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!")
}

}
}

我打开第二个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 返回到第一个 ViewController?

self.navigationController?.popViewController(animated: false)  

最佳答案

如何在两个 ViewController 上调用 viewDidAppear 中的函数,以便每次在两个 View 之间切换时都能得到响应?您不需要在 ViewController 之间传递 networkService

override func viewDidAppear(_ animated: Bool) {

networkService!.onFunction = { result in
print("I got \(result) from the server!")
}

}

关于ios - 当两个 ViewController 打开时,如何在两个 ViewController 中接收相同的回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55819678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com