NotificationCenter in swift
A notification dispatch mechanism that enables the broadcast of information to registered observers.
—–Apple
NotificationCenter
in Swift is a mechanism for broadcasting information within a program. It allows objects to communicate with each other without needing to directly reference each other, which helps in maintaining a loose coupling between components. Here’s an overview of NotificationCenter
and how to use it:
Key Concepts
- NotificationCenter:
- A centralized hub through which notifications are broadcasted and received.
- Instances of
NotificationCenter
are responsible for managing the registration of observers and the posting of notifications.
- Notification:
- An object that encapsulates information that is broadcasted by a notification center.
- Notifications can carry additional information through a
userInfo
dictionary.
- Observer:
- An object that registers itself to receive notifications of a specific type.
- Name:
- Notification.Name(“com.user.register.success”)
- This is the Notification key and this should be unique for any new Notification register method. For calling the same method this should be the same. This key only can call this same method which we have registered as a key and lock .
Posting Notifications
To post a notification, use the post
method on the NotificationCenter
instance. You can post notifications with or without additional information.
// Without additional information
NotificationCenter.default.post(name: Notification.Name("com.user.register.success"), object: nil)
// With additional information
let userInfo: [String: Any] = ["key": "value"]
NotificationCenter.default.post(name: Notification.Name("com.user.register.success"), object: nil, userInfo: userInfo)
Adding Observers
To observe notifications, use the addObserver
method. You can specify the notification name and the action to take when the notification is received.
// Adding an observer
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: Notification.Name("MyNotification"), object: nil)
// The method that handles the notification
@objc func handleNotification(_ notification: Notification) {
if let userInfo = notification.userInfo {
// Process userInfo if needed
}
// Handle the notification
}
Removing Observers
It is essential to remove observers when they are no longer needed to avoid memory leaks.
// Removing an observer
NotificationCenter.default.removeObserver(self, name: Notification.Name("com.user.register.success"), object: nil)
Example
Here’s a complete example demonstrating how to post and observe notifications:
import UIKit
class PostViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Post a notification after 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
NotificationCenter.default.post(name: Notification.Name("com.user.register.success"), object: nil, userInfo: ["message": "Hello, World!"])
}
}
}
class ObserveViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Add observer for the notification
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: Notification.Name("com.user.register.success"), object: nil)
}
@objc func handleNotification(_ notification: Notification) {
if let userInfo = notification.userInfo, let message = userInfo["message"] as? String {
print("Received message: \(message)")
}
}
deinit {
// Remove observer when the view controller is deallocated
NotificationCenter.default.removeObserver(self, name: Notification.Name("com.user.register.success"), object: nil)
}
}
In this example, the PostViewController
posts a notification after a delay, and the ObserveViewController
listens for that notification and handles it when received. The observer is also removed in the deinit
method to prevent memory leaks.
Extension Of Notification:
extension Notification.Name {
static var loginSuccess: Notification.Name {
return .init(rawValue: "com.user.login.success") }
static var registerSuccess: Notification.Name {
return .init(rawValue: "com.user.register.success") }
}
Use Case –
Now in place of NSNotification.Name(“com.user.login.success”)
of you can write simply .loginSuccess
NotificationCenter.default
.addObserver(self,
selector:#selector(loginSuccess(_:)),
name: .loginSuccess,
object: nil)
How to use Object in NotificationCenter?
import UIKit
class PostViewController: UIViewController {
private let notificationCenter = NotificationCenter.default
override func viewDidLoad() {
super.viewDidLoad()
// Post a notification after 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
notificationCenter.post(name: .loginSuccess, object: nil, userInfo: ["message": "Hello, World!"])
}
}
}
class ObserveViewController: UIViewController {
private let notificationCenter = NotificationCenter.default
override func viewDidLoad() {
super.viewDidLoad()
// Add observer for the notification
notificationCenter.addObserver(self, selector: #selector(handleNotification(_:)), name: .loginSuccess, object: nil)
}
@objc func handleNotification(_ notification: Notification) {
if let userInfo = notification.userInfo, let message = userInfo["message"] as? String {
print("Received message: \(message)")
}
}
deinit {
// Remove observer when the view controller is deallocated
notificationCenter.removeObserver(self, name: .loginSuccess, object: nil)
}
}
@objc func loginSuccess(_ notification: Notification){
print(notification.object as? [String: Any] ?? [:])
print(notification.userInfo?["userInfo"] as? [String: Any] ?? [:]) }
Refferences:
https://developer.apple.com/documentation/foundation/notificationcenter
https://medium.com/@nimjea/notificationcenter-in-swift-104b31f59772
https://reintech.io/blog/mastering-swift-notification-center#
https://chatgpt.com/c/3da0f38f-13e8-4264-82f1-79ec08800330
Стильные заметки по созданию отличных видов на каждый день.
Заметки экспертов, события, все дропы и шоу.
https://femalemoda.ru/moda/2024-05-20-bottega-veneta-pouch-italyanskiy-vecherniy-shik/
Patek Philippe is a prestigious Swiss watchmaker known for its craftsmanship. Founded in 1839, the brand continues to uphold its tradition of superior craftsmanship. Horology aficionados seek out Patek Philippe due to its engineering feats and limited production.
https://patek.superpodium.com
На данном сайте доступны свежие промокоды для Lamoda. Активируйте их, чтобы сделать выгодную покупку на лучшие товары. Коды на скидку актуализируются ежедневно, чтобы вам всегда были доступны лучшими предложениями.
https://lamoda.fashionpromo.ru
4qps2f
ppcn2p
Trong cá cược bóng đá, việc nắm bắt thông tin thong ke bong da là vô cùng quan trọng để người chơi có thể đưa ra quyết định chính xác.
В нашем магазине можно купить оригинальные товары от Gucci . Большой выбор включает одежду и аксессуары , удовлетворяющие любые вкусы .
https://boutique.gucci1.ru
chquf8
priligy tablets price Age Group Adult Usage Application Muscle Building Packaging Size 100 mg ml Strength 100 mg Form Injection Brand Ma Xtreme Pharma Dose 100 mg Packaging Type Vial Testo Prop 10 Testosterone Propionate provides great gains of muscle and strength