gpt4 book ai didi

ios - 如何从 viewController 到 appdelegate 进行通信?

转载 作者:行者123 更新时间:2023-11-28 19:25:14 25 4
gpt4 key购买 nike

我想与我的 appdelegate 通信,换句话说,我想从多个 View 向 AppDelegate 发送数据,这可能吗?

我找到了这段代码

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

这个问题: Bi-Directional communication between ViewController and AppDelegate with swift 2 for iOS

有可能使用 NSNotification 进行通信吗?

最佳答案

是的,Notification 可以完成您想要做的事情。在 View Controller 中,发布通知:

class YourViewController: UIViewController {

...

@IBAction func buttonPressed(_ sender: Any) {
NotificationCenter.default.post(name: "ViewControllerButtonPressed", object: nil)
}
}

然后,在您的 AppDelegate 中,添加一个 Notification 观察者来观察此通知名称的帖子:

class AppDelegate: UIResponder, UIApplicationDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

...

//Add the observer
//This observer will call the "doSomething" function every time NotificationCenter.default.post(name: "ViewControllerButtonPressed", object: nil) is called
NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: "ViewControllerButtonPressed", object: nil)
}

@objc func doSomething() {
print("A button was pressed in one of your view controllers!")
}

}

附加建议:为了使事情更简单,您可以扩展 Notification.Name 来为名称创建静态 String 值:

public extension Notification.Name {
static let ButtonPressed = Notification.Name("ViewControllerButtonPressed")
}

这可以取代

NotificationCenter.default.post(name: "ViewControllerButtonPressed", object: nil)

NotificationCenter.default.post(name: NSNotification.Name.ButtonPressed, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: "ViewControllerButtonPressed", object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: NSNotification.Name.ButtonPressed, object: nil)

实现上述方法是可选的,但可以防止在使用 Notification 时出现拼写错误。

关于ios - 如何从 viewController 到 appdelegate 进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419459/

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