Skip to content

Latest commit

 

History

History
122 lines (114 loc) · 6.71 KB

19. Notification Center.md

File metadata and controls

122 lines (114 loc) · 6.71 KB

날짜: 2023-04-25 12:14

주제: 이벤트 알려주는 메시지


메모:

Notification Center

  • Notification은 앱의 다른 부분에게 어떤 이벤트가 발생했음을 알려주는 메시지를 의미한다.
  • Swift에서는 NotificationCenter를 통해 이를 처리할 수 있다.
  • Notification은 앱에서 여러 부분이 독립적으로 작동하고 있을 때 유용하다. 예를 들어, 사용자가 버튼을 눌렀을 때 다른 뷰 컨트롤러에 이를 알려야 하는 경우, 직접적으로 메시지를 전달하는 대신 notification을 사용할 수 있다.
  • NotificationCenter는 싱글톤 객체로, 앱에서 발생하는 특정 이벤트를 다른 객체에게 알리는 역할을 한다.
  • 객체는 NotificationCenter에 옵저버를 추가하여 특정 이벤트를 구독하고, 이벤트가 발생하면 NotificationCenter가 알림을 보낸다. Notification
Notification
  • 등록된 노티피케이션에 노티피케이션 센터를 통해 정보를 전달하기 위한 구조체입니다.
  • 주요 프로퍼티
  • name : 알림을 식별하는 태그
     var name: Notification.Name
  • object : 발송자가 옵저버에게 보내려고 하는 객체. 주로 발송자 객체를 전달하는 데 쓰임
     var object: Any?
  • userInfo : 노티피케이션과 관련된 값 또는 객체의 저장소
     var userInfo: [AnyHashable : Any]?
  • 예) 특정 행동으로 인해 작업이 시작되거나 완료되는 시점에 다른 인스턴스로 노티피케이션이 발생 시 필요한 데이터를 같이 넘겨 줄 수 있습니다.
  • 간단한 예로 네트워킹을 이용하는 애플리케이션이라면 네트워킹이 시작 및 완료되는 시점, 음악 및 동영상 재생 등에도 재생이 끝나는 시점에 관련 정보를 넘겨 줄 수 있습니다.
NotificationCenter
  • 등록된 옵저버에게 동시에 노티피케이션을 전달하는 클래스입니다.
  • NotificationCenter 클래스는 노티피케이션을 발송하면 노티피케이션 센터에서 메세지를 전달한 옵저버의 처리할 때까지 대기합니다. 즉, 흐름이 동기적(synchronous)으로 흘러갑니다. 노티피케이션을 비동기적으로 사용하려면 NotificationQueue를 사용하면 됩니다.
  • 기본 노티피케이션 센터 얻기
    • default : 애플리케이션의 기본 노티피케이션 센터입니다.
     class var `default`: NotificationCenter { get }
  • 옵저버 추가 및 제거
    • addObserver(forName:object:queue:using:) : 노티피케이션을 노티피케이션 대기열(Queue)과 대기열(Queue)에 추가할 블록(스위프트의 클로저), 노티피케이션 이름을 노티피케이션 센터의 메서드를 가리키는 장소(디스패치 테이블, Dispatch Table)에 이름을 추가합니다.
    • 여기서 object에 특정 객체를 명시하면 명시한 객체가 발송한 노티피케이션일 때에만 해당 이름의 노티피케이션을 수신합니다.
    func addObserver(forName name: NSNotification.Name?, 
                                           object obj: Any?, 
                                                 queue: OperationQueue?, 
                                         using block: @escaping (Notification) -> Void) -> NSObjectProtocol
    • addObserver(_:selector:name:object:) : 노티피케이션을 노티피케이션 센터의 메서드를 가리키는 장소에 이름을 추가합니다.
     func addObserver(_ observer: Any, 
                        selector aSelector: Selector, 
                               name aName: NSNotification.Name?, 
                           object anObject: Any?)
    • removeObserver(_:name:object:) : 노티피케이션 센터의 메서드를 가리키는 장소에서 일치하는 이름을 제거합니다.
    func removeObserver(_ observer: Any, 
                                    name aName: NSNotification.Name?, 
                                object anObject: Any?)
    • removeObserver(_:) : 노티피케이션 센터의 메서드를 가리키는 장소에서 모든 이름을 제거합니다.
     func removeObserver(_ observer: Any)
  • 노티피케이션 발송
  • post(_:) : 지정된 노티피케이션을 노티피케이션 센터에 발송합니다.
     func post(_ notification: Notification)
  • post(name:object:userInfo:) : 지정된 이름, 보낸 객체, 보낼 정보로 노티피케이션을 만들어 노티피케이션 센터에 발송합니다.
     func post(name aName: NSNotification.Name,
                  object anObject: Any?, 
     	      userInfo aUserInfo: [AnyHashable : Any]? = nil)
  • post(name:object:) : 지정된 이름, 보낸 객체로 노티피케이션을 만들어 노티피케이션 센터에 발송합니다.
    func post(name aName: NSNotification.Name, object anObject: Any?)

예제

일반 노티피케이션
// 옵저버 추가
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: NSNotification.Name("TestNotification"), object: nil)

// Notification 발송
NotificationCenter.default.post(name: NSNotification.Name("TestNotification"), object: nil)

// Notification을 받았을 때 실행할 메서드
@objc func handleNotification(_ notification: Notification) {
    print("Notification received!")
}
User Info 정보를 담은 노티피케이션
// 발송자 
let button = UIButton()
button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)

@objc func buttonClicked(_ sender: UIButton) { 
	let userInfo: [String: Any] = ["button": sender]
	NotificationCenter.default.post(name: NSNotification.Name("ButtonClickedNotification"), object: nil, userInfo: userInfo)
}
// 수신자 
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: NSNotification.Name("ButtonClickedNofication"), object: nil)

@objc func handleNotification(_ notification: Notification) { 
	if let button = notification.userInfo?["button"] as? UIButton { 
		print("Button clicked!")
	}
}

출처(참고문헌)

연결문서

  • [[4. IOS Basic Asynchronous Programming]]

Tag

  • #IOS/Asynchronous/Notification_Center