[swift] Swift에서 비동기 처리를 위한 알림(Notification) 활용 방법
앱 개발 과정에서 비동기적인 작업을 처리해야 하는 경우가 많습니다. Swift에서 비동기 작업을 처리하기 위한 다양한 방법 중 하나는 알림(Notification)을 사용하는 것입니다. 알림을 활용하면 작업의 완료 여부를 감지하고 결과를 처리할 수 있습니다.
1. 알림 생성 및 등록
Swift에서 알림을 만들기 위해서는 NotificationCenter
를 사용해야 합니다. 먼저, 알림을 받을 객체에서 알림을 등록해야 합니다. 다음은 알림을 등록하는 방법입니다.
// 알림을 받을 객체의 메서드를 정의
@objc func handleNotification(notification: Notification) {
// 알림을 처리하는 코드 작성
guard let result = notification.object as? String else { return }
print("Received notification with result: \(result)")
}
// 알림 등록
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification), name: NSNotification.Name("MyNotification"), object: nil)
2. 알림 발송
비동기 작업이 완료되고 알림을 보내려면 다음과 같이 post
메서드를 사용해서 알림을 발송합니다.
NotificationCenter.default.post(name: NSNotification.Name("MyNotification"), object: "Task Completed")
위의 예제에서는 “MyNotification”이라는 이름의 알림을 보내고, “Task Completed”라는 결과를 함께 전달하고 있습니다.
3. 알림 수신
알림을 수신하기 위해서는 앞서 등록한 handleNotification
메서드를 구현해야 합니다. 이 메서드에서 알림을 처리하는 로직을 작성합니다.
@objc func handleNotification(notification: Notification) {
// 알림을 처리하는 코드 작성
guard let result = notification.object as? String else { return }
print("Received notification with result: \(result)")
}
위의 예제에서는 알림을 수신하면 결과를 콘솔에 출력하고 있습니다.
4. 알림 해제
알림을 더 이상 수신받지 않고 해제하려면 다음과 같이 removeObserver(_:name:object:)
메서드를 사용합니다.
NotificationCenter.default.removeObserver(self, name: NSNotification.Name("MyNotification"), object: nil)
마치며
Swift에서 비동기 작업을 처리하기 위해 알림을 활용하는 방법을 알아보았습니다. 알림을 사용하면 작업의 완료 여부를 신속하게 감지하고 결과를 처리할 수 있습니다. 다양한 비동기 처리 시나리오에서 알림을 적절히 활용하여 개발 효율성을 높일 수 있습니다.
참고 자료
- Apple Developer Documentation - NotificationCenter
- SwiftLee - NSNotificationCenter를 NotificationCenter로 마이그레이션하기
- Hacking with Swift - How to post messages using NotificationCenter