EEYatHo 앱 깎는 이야기

Swift ) Background Foreground 감지 본문

iOS, Swift/Tip, Bug, Swift Error

Swift ) Background Foreground 감지

EEYatHo 2021. 3. 2. 21:14
반응형

[ NotificationCenter로 백그라운드 감지 ]

if #available(iOS 13.0, *) {
    NotificationCenter.default.addObserver(self, selector: #selector(taskFunc), name: UIScene.willDeactivateNotification, object: nil)
} else {
    NotificationCenter.default.addObserver(self, selector: #selector(taskFunc), name: UIApplication.willResignActiveNotification, object: nil)
}

 

 

[ NotificationCenter로 포그라운드 감지 ]

if #available(iOS 13.0, *) {
    NotificationCenter.default.addObserver(self, selector: #selector(taskFunc), name: UIScene.willEnterForegroundNotification, object: nil)
} else {
    NotificationCenter.default.addObserver(self, selector: #selector(taskFunc), name: UIApplication.willEnterForegroundNotification, object: nil)
}

 

[ 옵저버 죽이는거 잊지말기 ]

/// 옵저버 없애기
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}

 

[ AppDelegate로 백그라운드 감지 ]

func applicationDidEnterBackground(_ application: UIApplication) {
    /// Did background code..
}

 

[ AppDelegate로 포그라운드 감지 ]

func applicationWillEnterForeground(_ application: UIApplication) {
    /// Will foreground code..
}

 

 

[ RxSwift ]

NotificationCenter
    .default
    .rx
    .notification(UIApplication.willEnterForegroundNotification)
    //.subscribeOn(MainScheduler.instance) UI작업일 경우 추가
    .subscribe(onNext: { [weak self] (aNotification) in
        print(aNotification)
    })
    .disposed(by: disposeBag)
Comments