[Swift] NotificationCenter 에 대해서...

Oni·2023년 11월 1일
0

기술면접

목록 보기
13/13
post-thumbnail

NotificationCenter를 사용하여 뷰컨트롤러 간에 데이터를 전달하는 방법은 간단하면서도 효과적이다. 아래는 NotificationCenter를 이용하여 데이터를 전달하는 구체적인 단계이다.

1. 데이터 전달 이벤트 정의

데이터를 전달할 이벤트를 정의하고, 필요한 데이터를 함께 전달한다. 이 이벤트는 Notification Name을 사용하여 식별된다.

extension Notification.Name {
    static let dataTransferEvent = Notification.Name("DataTransferEvent")
}

2. 데이터를 보내는 뷰컨트롤러에서 이벤트 발송

데이터를 보내는 뷰컨트롤러에서 NotificationCenter를 사용하여 이벤트를 발송한다.

class SenderViewController: UIViewController {
    func sendData() {
        let data: [String: Any] = ["key": "Hello from Sender"]
        NotificationCenter.default.post(name: .dataTransferEvent, object: nil, userInfo: data)
    }
}

3. 데이터를 받는 뷰컨트롤러에서 이벤트 수신

데이터를 받는 뷰컨트롤러에서 NotificationCenter를 사용하여 이벤트를 수신하고 데이터를 처리합니다.

class ReceiverViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(handleDataTransferEvent(_:)), name: .dataTransferEvent, object: nil)
    }

    @objc func handleDataTransferEvent(_ notification: Notification) {
        if let data = notification.userInfo as? [String: Any],
           let receivedData = data["key"] as? String {
            print("Received data: \(receivedData)")
            // 수신된 데이터를 처리
        }
    }
}

위 코드에서 SenderViewController에서 sendData() 메서드를 호출하면 ReceiverViewController의 handleDataTransferEvent(_:) 메서드가 호출되어 데이터를 수신하고 처리한다. NotificationCenter를 사용하면 여러 뷰컨트롤러 간에 간단하게 데이터를 전달할 수 있다.


실제 사용 예제

금번 최종 프로젝트 때 사용한 Notification에 대해 아래와 같이 코드를 발췌하였다.

class EmotionTrashService {

	// 이전 코드
	...

	// auto delete: 유저의 감정쓰레기 자동 삭제
    func autoDeleteEmotionTrash(_ user: User, _ day: Int) {
        let totalEmotionTrashes = fetchTotalEmotionTrashes(user)
        let calendar = Calendar.current
        
        for emotionTrash in totalEmotionTrashes {
            if let trashDate = emotionTrash.timestamp {
                if calendar.isDate(trashDate, inSameDayAs: calendar.date(byAdding: .day, value: -day, to: Date())!) {
                    deleteEmotionTrash(user, emotionTrash.id!)
                }
            }
        }
        // "EmotionTrashUpdate"라는 이름으로 이벤트 발송
        NotificationCenter.default.post(name: NSNotification.Name("EmotionTrashUpdate"), object: nil)
    }
}
    
    
 class HomeViewController: RootViewController<HomeView> {
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
        
        // 데이터를 받는 뷰컨에서 이벤트 수신
        NotificationCenter.default.addObserver(self, selector: #selector(handleEmotionTrashUpdateNotification), name: NSNotification.Name("EmotionTrashUpdate"), object: nil)
        
        // 이전 코드
        ...
        
        // 이벤트 수신 후 데이터 업데이트 로직
        @objc func handleEmotionTrashUpdateNotification() {
        rootView.emotionCount = EmotionTrashService.shared.fetchTotalEmotionTrashes(SignInService.shared.signedInUser!).count
        DispatchQueue.main.async {
            self.rootView.updateEmotionTrashesCountLabel(self.rootView.emotionCount)
        }
    }
}
profile
하지만 나는 끝까지 살아남을 거야!

0개의 댓글