ios 处理 applicationDidBecomeActive - “视图控制器如何响应应用程序变为活动状态?”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3639859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:39:31  来源:igfitidea点击:

Handling applicationDidBecomeActive - "How can a view controller respond to the app becoming Active?"

iosiphoneios4multitaskinguiapplicationdelegate

提问by Calvin

I have the UIApplicationDelegateprotocol in my main AppDelegate.m class, with the applicationDidBecomeActivemethod defined.

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

I want to call a method when the application returns from the background, but the method is in another view controller. How can I check which view controller is currently showing in the applicationDidBecomeActivemethod and then make a call to a method within that controller?

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

回答by Reed Olsen

Any class in your application can become an "observer" for different notifications in the application. When you create (or load) your view controller, you'll want to register it as an observer for the UIApplicationDidBecomeActiveNotificationand specify which method that you want to call when that notification gets sent to your application.

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

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

Don't forget to clean up after yourself! Remember to remove yourself as the observer when your view is going away:

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

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

More information about the Notification Center.

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

回答by igrek

Swift 3, 4 Equivalent:

Swift 3、4 等效项:

adding observer

添加观察者

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

removing observer

移除观察者

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

callback

打回来

@objc func applicationDidBecomeActive() {
    // handle event
}

回答by Zorayr

Swift 2 Equivalent:

Swift 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.
}

回答by Abhishek Jain

Swift 4.2

斯威夫特 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() {
}

回答by CodeBender

With Swift 4, Apple advises via a new compiler warning that we avoid the use of #selectorin this scenario. The following is a much safer way to accomplish this:

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

First, create a lazy var that can be used by the notification:

首先,创建一个可以被通知使用的惰性变量:

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

If you require the actual notification be included, just replace the _with notification.

如果您需要实际通知被收录,只需更换_notification

Next, we set up the notification to observe for the app becoming active.

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

func setupObserver() {
    _ = NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive,
                                               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.

这里的重大变化是#selector我们现在调用上面创建的 var而不是调用 a 。这可以消除无效选择器崩溃的情况。

Finally, we remove the observer.

最后,我们移除观察者。

func removeObserver() {
    NotificationCenter.default.removeObserver(self, name: .UIApplicationDidBecomeActive, object: nil)
}

回答by Gurjinder Singh

Swift 5

斯威夫特 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
    }

回答by ollie

The Combine way:

组合方式:

import Combine

var cancellables = Set<AnyCancellable>()
NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
    .sink { notification in
            // do stuff
    }.store(in: &cancellables)