iOS notification center screen 보여질 때 didBecomeActiveNotification 호출되는 문제

냠냠·2022년 5월 24일
1

iOS

목록 보기
2/4

문제 - iOS 화면 상단을 손가락으로 쓸어내리면 (swipe down) 알림 센터가 보여지게 된다. 이때 화면 하단으로 알림 센터를 완전히 내리게 되면 didBecomeActiveNotification 이 호출 되버린다.

    1. 화면 상단을 쓸어내려 알림 센터가 보이기 시작하면 willResignActiveNotification 호출
    1. 화면 하단 끝가지 알림 센터를 내리면 didBecomeActiveNotification, willResignActiveNotification 가 순서대로 호출된다.

임시 해결 방법 - didBecomeActiveNotification 이후 willResignActiveNotification 가 바로 호출 되므로 약간의 딜레이를 줘서 해결. 아래 코드를 참조 바란다.

	private var appDidBecomeActiveWorkItem: DispatchWorkItem?

    func addForegroundObservers() {
        guard applicationDidBecomeActiveObserver == nil else { return }
        applicationDidBecomeActiveObserver = NotificationCenter
            .default
            .addObserver(forName: UIApplication.didBecomeActiveNotification,
                         object: nil,
                         queue: nil) { [weak self] _ in
                guard let self = self else { return }
                self.appDidBecomeActiveWorkItem = DispatchWorkItem {
                    // do something
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.02, execute: self.appDidBecomeActiveWorkItem!)
        }
    }
    
    func addBackgroundObservers() {
        if applicationWillResignActiveObserver == nil {
            applicationWillResignActiveObserver = NotificationCenter
                .default
                .addObserver(forName: UIApplication.willResignActiveNotification,
                             object: nil,
                             queue: nil) { [weak self] _ in
                    guard let self = self else { return }
                    self.appDidBecomeActiveWorkItem?.cancel()
                    self.appDidBecomeActiveWorkItem = nil
                    // do something
            }
        }
    }

0개의 댓글