-
iOS [Swift] - NotificationCenter 사용하기iOS Develop 2022. 3. 20. 19:58반응형
이번 글에서는 NotificationCenter를 알아보겠습니다! :-)
NotificationCenter
- NotificationCenter는 우체국 이라고 생각하면 편합니돠!
- A 객체에서는 우체국으로 이벤트를 Post (발송) 해줍니다.
- B 객체는 우체국에 "누구든 우리 주소로 보내는 우편물은 우리에게 보내줘!" 라고 Observer를 등록해놓습니다.
- 우체국(NotificationCenter)은 A가 Post(발송)한 이벤트를 가지고 있다가 주소지에 담긴 Observer에 전달을 해주는 역할을 합니다.
- 이 때, B 객체는 전달된 이벤트를 확인하고, 이에 관련된 작업을 해주면 되는 것입니다!
좋습니다. 그러면 우리가 가장 먼저 해야할 것은 무엇인가??!!
NotificationCenter를 활용해서 처리할 이벤트를 식별하기 위해 이름을 붙여주겠습니다.
// MARK: - Notification Name Set extension Notification.Name { /// extension 안에는 저장 프로퍼티를 생성하면 안되기에 static을 붙임 static let notiName = Notification.Name("notificationName") }
Next Stage!!
어디선가 객체를 보냈을 때, 이를 처리해야하기 때문에 우리의 주소지를 우체국에 등록해주겠습니다. (+ 처리할 함수의 이름도 포함 ^_^)
override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(NotiAlarm(_:)), name: .notiName, object: nil) }selector에 들어가 있는 것이 처리할 함수의 이름입니다!
Next Stage!!
등록을 해주었으면 처리할 함수를 작성 해주어야겠지요?
저는 이벤트를 post해주는 부분에서 문자열을 담아서 보낼 것이기 때문에 그것을 받아서 Label에 넣어주겠습니다.
@objc func NotiAlarm(_ notification: Notification) { guard let textString = notification.object as? String else { return } lbl_Text.text = textString }NotificationCenter Observer에 등록할 때 사용할 함수는 반드시 @objc를 붙여주어야합니다!
(아마 NotificationCenter가 Obj-c에서 사용되었던 녀석이었기 때문에 붙여주는 것으로 알고있스무니다..!)
좋아요! 거의 다왔습니다.
이제 대망의 post하기!!! 앞서 말했지만, 저는 post할 때 단순 이벤트만 보내는 것이 아니라 object를 담아서 보내겠습니다.
은근히 요 object가 쏠쏠하게 쓰이더라구요 크크..!!
저는 post를 두 번 보내보겠습니다. Label에 Notification Post가 왔다고 text를 보내주는 것과, Label의 text를 지우는 이벤트!!
@IBAction func doIt_Noti(_ sender: UIButton) { NotificationCenter.default.post(name: .notiName, object: "Notification 알람 전송!!!") } @IBAction func removeText(_ sender: UIButton) { NotificationCenter.default.post(name: .notiName, object: "") }이렇게 object에 무언가를 담아서 보내면 위에서처럼 notification을 인자로 받아서 꺼내 쓰시면 됩니다 ㅎㅎ
전체 코드
/// ViewController.swift import UIKit class ViewController: UIViewController { @IBOutlet weak var lbl_Text: UILabel! override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(NotiAlarm(_:)), name: .notiName, object: nil) } @IBAction func next_Btn(_ sender: UIButton) { guard let controller = self.storyboard?.instantiateViewController(withIdentifier: "secondVC") as? SecondViewController else { return } print("press") self.navigationController?.pushViewController(controller, animated: true) } @objc func NotiAlarm(_ notification: Notification) { guard let textString = notification.object as? String else { return } lbl_Text.text = textString } } // MARK: - Notification Name Set extension Notification.Name { /// extension 안에는 저장 프로퍼티를 생성하면 안되기에 static을 붙임 static let notiName = Notification.Name("notificationName") }/// SecondViewController.swift import UIKit class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func doIt_Noti(_ sender: UIButton) { NotificationCenter.default.post(name: .notiName, object: "Notification 알람 전송!!!") } @IBAction func removeText(_ sender: UIButton) { NotificationCenter.default.post(name: .notiName, object: "") } }
NotificationCenter 동작 영상
마치며
- 이번 포스팅에서는 NotificationCenter에 대해서 다뤄보았습니다.
- NotificationCenter는 이래저래 많이 사용되지만, 호출 시점이 불명확하다고 생각하여 조심스럽게 사용하게 되는 것 같습니다..!!
- 그렇기 때무네 확실하게 사용할 수 있을 경우에 알맞게 사용하시면 좋을 것 같습니다!! 유용한 녀석!!
'iOS Develop' 카테고리의 다른 글
iOS [Swift] - WatchOS HealthKit Background (0) 2022.03.23 iOS [Swift] - WatchOS 화면 Push & 값 전달하기 (0) 2022.03.21 iOS [Swift] - Toast Message (0) 2022.03.17 iOS [Swift] - Delegate Pattern (델리게이트 패턴) (0) 2022.03.09 iOS [Swift] - Alamofire 통신 (0) 2022.03.09