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

标签 ios swift appdelegate

我想与我的 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/

相关文章:

objective-c - iOS 从后台加载时重新检查位置

ios - 使用 Swift (LinkedIn API) 将 JSON 响应解析为数据模型

ios - 如何在collectionView轮廓之外显示标签

ios - 当应用程序被杀死时,位置不会在行走时更新

ios - Xcode - 如何修复 'NSUnknownKeyException' ,原因 : … this class is not key value coding-compliant for the key X"error?

iphone - iOS查看 'folding'动画

ios - 应用程序在没有协议(protocol)功能的情况下编译 - 为什么?

ios - 导航 Controller 的最佳实践

Swift:文本标签未更新

ios - 使用乘法混合模式覆盖 UIImageViews?