188

UIApplicationDelegate我的主 AppDelegate.m 类中有协议,并applicationDidBecomeActive定义了方法。

我想在应用程序从后台返回时调用一个方法,但该方法在另一个视图控制器中。如何检查方法中当前显示的视图控制器applicationDidBecomeActive,然后调用该控制器中的方法?

4

11 回答 11

313

应用程序中的任何类都可以成为应用程序中不同通知的“观察者”。当您创建(或加载)您的视图控制器时,您需要将其注册为观察者,UIApplicationDidBecomeActiveNotification并指定当通知发送到您的应用程序时要调用的方法。

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(someMethod:)
                                             name:UIApplicationDidBecomeActiveNotification object:nil];

不要忘记清理自己!当您的视图消失时,请记住将自己移除为观察者:

[[NSNotificationCenter defaultCenter] removeObserver:self 
                                                name:UIApplicationDidBecomeActiveNotification
                                              object:nil];

有关通知中心的更多信息。

于 2010-09-03T22:10:10.763 回答
82

Swift 3、4 等效:

添加观察者

NotificationCenter.default.addObserver(self,
    selector: #selector(applicationDidBecomeActive),
    name: .UIApplicationDidBecomeActive, // UIApplication.didBecomeActiveNotification for swift 4.2+
    object: nil)

移除观察者

NotificationCenter.default.removeObserver(self,
    name: .UIApplicationDidBecomeActive, // UIApplication.didBecomeActiveNotification for swift 4.2+
    object: nil)

打回来

@objc func applicationDidBecomeActive() {
    // handle event
}
于 2016-09-28T13:35:46.643 回答
16

斯威夫特 2 等效

let notificationCenter = NSNotificationCenter.defaultCenter()

// Add observer:
notificationCenter.addObserver(self,
  selector:Selector("applicationWillResignActiveNotification"),
  name:UIApplicationWillResignActiveNotification,
  object:nil)

// Remove observer:
notificationCenter.removeObserver(self,
  name:UIApplicationWillResignActiveNotification,
  object:nil)

// Remove all observer for all notifications:
notificationCenter.removeObserver(self)

// Callback:
func applicationWillResignActiveNotification() {
  // Handle application will resign notification event.
}
于 2015-08-16T18:59:49.247 回答
11

Swift 5

fileprivate  func addObservers() {
      NotificationCenter.default.addObserver(self,
                                             selector: #selector(applicationDidBecomeActive),
                                             name: UIApplication.didBecomeActiveNotification,
                                             object: nil)
    }

fileprivate  func removeObservers() {
        NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
    }

@objc fileprivate func applicationDidBecomeActive() {
// here do your work
    }
于 2019-12-08T11:31:15.700 回答
7

Swift 4.2

Add observer-

NotificationCenter.default.addObserver(self, selector: #selector(handleEvent), name: UIApplication.didBecomeActiveNotification, object: nil)

Remove observer-

NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)

Handle Event-

@objc func handleEvent() {
}
于 2018-11-10T15:32:47.997 回答
6

对于 Swift 4,Apple 通过一个新的编译器警告建议我们避免#selector在这种情况下使用。以下是实现此目的的更安全的方法:

首先,创建一个变量来保存观察者实例(将用于取消它):

var didBecomeActiveObserver: NSObjectProtocol

然后创建一个可以被通知使用的惰性变量:

lazy var didBecomeActive: (Notification) -> Void = { [weak self] _ in
    // Do stuff
} 

如果您需要包含实际通知,只需将 替换_notification

接下来,我们设置通知以观察应用程序是否处于活动状态。

func setupObserver() {
    didBecomeActiveObserver = NotificationCenter.default.addObserver(
                                  forName: UIApplication.didBecomeActiveNotification,
                                  object: nil,
                                  queue:.main,
                                  using: didBecomeActive)
}

The big change here is that instead of calling a #selector, we now call the var created above. This can eliminate situations where you get invalid selector crashes.

Finally, we remove the observer.

func removeObserver() {
    NotificationCenter.default.removeObserver(didBecomeActiveObserver)
}
于 2018-03-02T16:48:14.587 回答
4

The Combine way:

import Combine

var cancellables = Set<AnyCancellable>()
NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
    .sink { notification in
            // do stuff
    }.store(in: &cancellables)
于 2020-03-19T14:23:49.427 回答
4

Swift 5 version:

 NotificationCenter.default.addObserver(self,
                                               selector: #selector(loadData),
                                               name: UIApplication.didBecomeActiveNotification,
                                               object: nil)

Removing the observer is no longer required in iOS 9 and later.

于 2020-08-31T11:48:45.923 回答
4

In Swift 5

override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)

         NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
    
         NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        }
    
    override func viewWillDisappear(_ animated: Bool) { 
        super.viewWillDisappear(animated)

        NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)

        NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
    }


@objc private func applicationWillResignActive() {
    }

    @objc private func applicationDidBecomeActive() {
    }
于 2021-02-01T05:56:31.913 回答
1

If any of you is using SwiftUI:

.onReceive(NotificationCenter.default.publisher(
    for: UIApplication.didBecomeActiveNotification)) { _ in
        print("DID BECOME ACTIVE")
    }
)
于 2020-11-06T02:13:04.593 回答
1

For Swift5 MacOS, you need to use NSApplication instead of UIApplication.

NotificationCenter.default.addObserver(self,
                                       selector: #selector(applicationDidBecomeActive),
                                       name: (NSApplication.didBecomeActiveNotification),
                                       object: nil)
    }
于 2021-03-03T05:55:54.970 回答