기타/iOS🍎

[iOS/Swift] Notification Center를 이용해 View Controller 간 데이터 전달하기

yujindonut 2022. 6. 13. 14:45
728x90

1. 알림을 Notification Center에 post하기

name : 전달하고자 하는 신호이름

object : 전달하고자 하는 데이터 넣는 곳, 없으면 nil

userInfo : Notification과 관련된 값 또는 객체의 저장소를 넣어줌, 없으면 nil


2. Notification Center에게 알림과 신호를 받기 위해서 Observer 등록하기 ( 알림을 받는 View Controller 에서 )

addObsever를 하면, Notification Center에 누가 알림을 보내면 Observer를 등록해 놓은 사람(View Controller)에 알림을 전달해줌

 

name : observer를 등록할 notification 이름 (post할때, 등록했던 notification 이름을 넣어줌)

object : observer가 해당 object의 notification만 전달 받고 싶을때, nil일 경우 해당하는 신호를 모두 받겠다는 의미

queue : block이 실행되는 작업 대기열 ( nil일 경우 동기적으로 실행 )

block : 알림을 받을 때 실행된느 블록

 

observer : 관찰자로 등록할 개체

selector : 해당 신호를 받으면 실행할 함수

name : observer를 등록할 notification 이름

object : observer가 해당 object의 notification만 전달받고 싶을때, nil일 경우는 해당하는 신호를 모두 받겠다는 의미


1. UI 준비 하기 !

배열을 이용해 하나의 집합으로

Outlet Collection을 이용하면, 반복되는 요소, 타입의 UI 컴포넌트가 있다면 라인수를 줄일 수 있다!

2. 알림을 전달하는 View Controller에서 Notification Center에 알림 전달하기

    @IBAction func fireOnTapped(_ sender: UIButton) {
        
        NotificationCenter.default.post(name: Notification.Name("Fire"), object: "불 났어요!!")
//        object에는 어떤것도 들어갈 수 있다.
    }

3. 알림을 받는 View Controller에서 알림 받을 준비하기

class SecondViewController: UIViewController {

    @IBOutlet var fires: [UIImageView]!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        fires.forEach { $0.isHidden = true }
        //불이 나면, 불UI가 보이도록 설정한다.
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(notiReceived),
                                               name: NSNotification.Name("Fire"),
                                               object: nil)
        //불이 꺼졌다는 신호를 받으면, 불UI가 사라지도록 설정한다.                                    
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(notiOffRecieved), name: NSNotification.Name("OFF"),
                                               object: nil)
    }
    // 알림을 받았을 때 실행하는 함수
    @objc func notiOffRecieved(notification:NSNotification) {
        if let notification = notification.object {
            print(notification)
        }
        fires.forEach{ $0.isHidden = true }
    }
    
    @objc func notiReceived(notification: NSNotification) {
        if let notification = notification.object {
            print(notification)
        }
        fires.forEach { $0.isHidden = false }
    }
}
728x90