ios监听程序进入后台和切换到前台

745 阅读1分钟

注册通知


   //监听程序进入前台和后台
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(enterBackGround:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(enterForeGround:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];




前后台切换时进入回调


- (void)enterBackGround:(NSNotificationCenter *)notification{
    MALog(@"程序进入了后台");
}
- (void)enterForeGround:(NSNotificationCenter *)notification{
    MALog(@"程序进入了前台");
}



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

 @objc func applicationDidBecomeActive(notification: NSNotification) {
        // Application is back in the foreground

        print("applicationDidBecomeActive")
    }