투케이2K

56. (ios/swift) NotificationCenter 노티피케이션 센터 사용해 브로드 캐스트 이벤트 알림 처리 본문

IOS

56. (ios/swift) NotificationCenter 노티피케이션 센터 사용해 브로드 캐스트 이벤트 알림 처리

투케이2K 2021. 11. 25. 15:56
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT

 

[소스 코드]

==========================================
// [AppDelegate : 일정 시간 후 작업 수행 : post delayed]
==========================================

DispatchQueue.main.asyncAfter(deadline: .now() + 10) { // [2초 후에 동작 실시]
    print("")
    print("===============================")
    print("[AppDelegate >> 노티피케이션 알림 송신]")
    print("===============================")
    print("")

    // [노티피케이션 알림 전송 실시]
    NotificationCenter.default.post(
         name: NSNotification.Name(rawValue: "notiData"), // 알림을 식별하는 태그
         object: nil, // 발송자가 옵저버에게 보내려고 하는 객체
         userInfo: ["testKey" : "hello"] // 객체의 저장소 [AnyHashable: Any] 형태
    )

}








==========================================
// [A_Main : 뷰 컨트롤러]
==========================================

// MARK: - [뷰 화면 표시]
override func viewDidAppear(_ animated: Bool) {
   super.viewDidAppear(animated)
   print("")
   print("===============================")
   print("[A_Main >> viewDidAppear() :: 뷰 화면 표시]")
   print("===============================")
   print("")
        
   // [앱 딜리게이트 노티피케이션 알림 확인 등록]
   NotificationCenter.default.addObserver(
       self, // 뷰 컨트롤러
       //selector: #selector(appDelegateCall), // userInfo 데이터 없는 경우 : @objc func appDelegateCall() {}
       selector: #selector(appDelegateCall(_:)), // userInfo 데이터 있는 경우 : @objc func appDelegateCall(_ notification:NSNotification) {}
       name: NSNotification.Name("notiData"), // 알림 식별자
       object: nil // 객체
   )
}


// MARK: - [뷰 종료 상태]
override func viewDidDisappear(_ animated: Bool) {
   super.viewDidDisappear(animated)
   print("")
   print("===============================")
   print("[A_Main >> viewDidDisappear() :: 뷰 종료 상태]")
   print("===============================")
   print("")
        
   // [앱 딜리게이트 노티피케이션 알림 확인 해제]
   NotificationCenter.default.removeObserver(self, name: NSNotification.Name("notiData"), object: nil)

}


// MARK: - [앱 딜리게이트에서 전달 받은 내용 처리 메소드]
@objc func appDelegateCall(_ notification:NSNotification) {
    print("")
    print("===============================")
    print("[A_Main >> appDelegateCall() :: 앱 딜리게이트 노티피케이션 수신 확인]")
    print("data :: \(notification.userInfo!["testKey"]!)")
    print("===============================")
    print("")
}
 

[결과 출력]


반응형
Comments