Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] NotificationCenter (background에서 foreground 진입 이벤트) 본문

iOS 기본 (swift)

[iOS - swift] NotificationCenter (background에서 foreground 진입 이벤트)

jake-kim 2021. 6. 2. 22:57

NotificationCenter

  • 특정 코드에 데이터를 보내고 싶은 경우나, 특정 이벤트를 받고 싶은 경우 사용
  • post하는 부분과 addObserver부분이 존재
    • post: 노티 전송
    • addObserver: 노티 받는 입장

사용 방법

  • 노티 구분은 Notification.Name 객체로 구분하므로, 사용할 노티 이름 설정
extension Notification.Name {
    static let print = NSNotification.Name("print")
}
  • post 부분
NotificationCenter.default.post(name: .print, object: nil)
  • addObserver부분 (이벤트를 받을 부분)
NotificationCenter.default.addObserver(self, selector: #selector(printSome), name: .print, object: nil)

...

    @objc func printSome() {
        print("print!!")
    }
  • 계속 addObserver하고 있는 형태이므로 removeObserver필요
    @objc func printSome() {
        print("print!!")
        NotificationCenter.default.removeObserver(self, name: .print, object: nil)
    }

* 전체 코드

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(printSome), name: .print, object: nil)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            NotificationCenter.default.post(name: .print, object: nil)
        }
    }

    @objc func printSome() {
        print("print!!")
        NotificationCenter.default.removeObserver(self, name: .print, object: nil)
    }

}

extension Notification.Name {
    static let print = NSNotification.Name("print")
}

background에서 foreground 진입 이벤트

  • background -> foreground로 이동한 경우 Notification.Name은 UIApplication객체에서 제공하는것 사용
    • UIApplication.willEnterForegroundNotification
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(printForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

    }

    @objc func printForeground() {
        print("entered foreground")
        NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
    }

}
  • 시스템 설정 후 다시 앱으로 돌아온 경우, 이벤트를 처리하기 위해서 위와같이 사용
Comments