【问题标题】:How do a comunication from viewController to appdelegate?如何从 viewController 到 appdelegate 进行通信?
【发布时间】:2019-12-20 03:22:17
【问题描述】:

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

我找到了这段代码

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

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

可以用 NSNotification 进行通信吗?

【问题讨论】:

  • 很高兴知道发送信息的原因。根据您的需要,信息可以在控制器之间共享,或者使用 UserDefaults 或 CoreData 永久存储。关于您想要传递什么类型的信息的一些背景知识会很有帮助。它是您设计的类/结构吗?
  • 是的,可以使用 NSNotification 也可以不使用 NSNotification

标签: ios swift appdelegate


【解决方案1】:

是的,Notification 可以做你想做的事。在视图控制器中,发布通知:

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)

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

【讨论】:

    【解决方案2】:

    我不建议您使用通知中心。它们有一些限制。

    1. 从每个 ViewController 中,您必须使用 post 功能,并且在 App Delegate 中您必须添加观察者。那么只有你可以使用 NotificationCenter 的 post 方法。就像上面大卫向你展示的那样。

    2. 如果您必须从不同的视图控制器调用 App Delegate 的不同功能,那么您必须再次在 App Delegate 中添加不同的观察者。之后就可以调用App delegate的不同功能了。

    但是使用您在问题中定义的上述方法。您不需要添加观察者。借助此实例,您可以调用 App 委托的任何方法。我给你举个例子:-

     let appDelegate = UIApplication.shared.delegate as! AppDelegate
    
     @UIApplicationMain
     @objc class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    var isUpdate: Bool = false
    
    func setValuesOfAppDelegate() {
        print("123")
    }
    
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
        IQKeyboardManager.shared.enable = true
    
        if UserDefaults.standard.bool(forKey: UserDefaultKey.isAutoLogin) == false {
            startViewController()
        } else {
            goToRootViewAfterLogin()
        }
    
        AppUserDefaults.set(KEnglish, forKey: KSetLanguage)
        self.registerForPushNotifications(application)
    
        return true
      }
    }
    

    示例如何使用 App 委托实例中的 App 委托变量和函数。你可以看一下代码。

    1. 在第一个示例中,我从 ClassA 设置 App Delegate 的变量。

    2. 在第二个示例中,我能够从 ClassB 调用 App Delegate 的函数。

    3. 在第三个示例中,我能够设置 App Delegate Class 变量的值,并能够同时访问该函数。

      class ClassA: UIViewController {
      
          //MARK:- View Life Cycle
          override func viewDidLoad() {
            super.viewDidLoad()
              appDelegate.isUpdate = true
          }
      }
      
      class ClassB: UIViewController {
      
           //MARK:- View Life Cycle
           override func viewDidLoad() {
             super.viewDidLoad()
              appDelegate.setValuesOfAppDelegate()
           }   
      }
      
      class ClassC: UIViewController {
      
           //MARK:- View Life Cycle
           override func viewDidLoad() {
             super.viewDidLoad()
              appDelegate.isUpdate = true
              appDelegate.setValuesOfAppDelegate()
          } 
       }
      

    【讨论】:

    • 在这个例子中,你是直接从视图控制器中访问 AppDelegate 吗?如果是这样,这基本上不是一个单例,你必须调用类似AppDelegate.appDelegate.isUpdate = true 而不是简单的appDelegate.isUpdate = true?
    • 是的,我直接在视图控制器中访问 appDelegate。如果您想在 Struct 中创建 AppDelegate 的实例,这取决于您。你可以这样做,但我试图解释通知中心和 AppDelegate 类之间的区别。
    猜你喜欢
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多