Swift 와 Combine을 익히기 위해 평소에 자주 사용하는 앱인 '알라미' 앱을 비슷하게 구현해보고 있다.
홈화면에서 우측하단
Floating Button
을 누르면 새로운 알람을 만들 수 있는 구조이다.
Storage
에 새로운 알람 데이터를 저장하는 것까지는 구현을 했는데,
모달이 닫혔을 때, 홈화면에 데이터가 업데이트가 안되는 것이다..! 😱
이런저런 삽질을 하다 구글링을 해서 해결책을 찾았다 !!!! 🎉
모달을 띄우는 ViewController에서 viewWillDisappear
함수 내에 아래 코드를 사용하여 NotificationCenter
을 보내준다.
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.post(name: NSNotification.Name("ModalDismissNC"), object: nil, userInfo: nil)
}
홈화면 ViewController의 viewDidLoad
에서 NotificationCenter
의 observer를 추가한다.
(⭐️ post할 때 사용한 NSNotification.Name과 동일한 이름으로 추가해야 한다!)
그리고 selector
메서드에서 UICollectionView를 업데이트하는 함수를 실행한다. 이때, DispatchQueue
를 이용해서 main 스레드에서 실행할 수 있도록 한다.
@IBOutlet weak var collectionview: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(self.didDismissDetailNotification(_:)),
name: NSNotification.Name("ModalDismissNC"),
object: nil
)
}
@objc func didDismissDetailNotification(_ notification: Notification) {
DispatchQueue.main.async {
self.viewModel.fetch()
}
}
https://github.com/someng2/MyAlarmy