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
can i order generic cytotec for sale In a series of 35 pelvic abscesses that resulted from PID, Worthen and Gunning demonstrated a success rate of 94 by aspiration drainage of 26 abscesses ranging from 2- 11 cm in size, while catheter drainage of 9 abscesses ranging from 7
m58wsd
Ищите в гугле
y5grkn
На этом сайте вы найдёте полезную информацию о способах лечения депрессии у пожилых людей. Вы также узнаете здесь о методах профилактики, актуальных подходах и советах экспертов.
http://matsutas.com/economic-development/development-for-somebody-else-by-alexander-obom/
На данном сайте вы сможете найти полезную информацию о способах лечения депрессии у пожилых людей. Вы также узнаете здесь о методах профилактики, актуальных подходах и рекомендациях специалистов.
http://forum.spolokmedikovke.sk/viewtopic.php?f=3&t=132676
На данном сайте вы сможете найти полезную информацию о способах лечения депрессии у пожилых людей. Также здесь представлены профилактических мерах, современных подходах и советах экспертов.
http://www.vandenbergelsloo.nl/uncategorized/website-in-de-lucht/
На данном сайте вы найдёте полезную информацию о витаминах для поддержания здоровья мозга. Кроме того, вы найдёте здесь рекомендации специалистов по приёму эффективных добавок и их влиянию на когнитивных функций.
https://jasper8xd0a.howeweb.com/32717361/fascination-О-витамины-для-мозга
vb8dfg
На этом сайте можно найти информацией о сериале “Однажды в сказке”, развитии событий и главных персонажах. на этом сайте Здесь размещены подробные материалы о создании шоу, актерах и фактах из-за кулис.
Программа наблюдения за объектами – это современный инструмент для обеспечения безопасности , сочетающий инновации и простоту управления.
На сайте вы найдете детальные инструкции по настройке и установке систем видеонаблюдения, включая облачные решения , их сильные и слабые стороны.
Облачное видеонаблюдение
Рассматриваются комбинированные системы, сочетающие облачное и локальное хранилище , что делает систему универсальной и эффективной.
Важной частью является разбор ключевых интеллектуальных возможностей, таких как определение активности, распознавание объектов и другие AI-технологии .
Промокоды — это специальные коды, дающие выгоду при покупках.
Они применяются в интернет-магазинах для снижения цены.
https://mamadona.ru/blogs/promokody_kak_sdelat_shoping_eshyo_prijatnee_i_vygodnee/
На этом сайте вы сможете получить действующие промокоды на товары и услуги.
Используйте их, чтобы сократить расходы на заказы.
I was struggling with setting up communication between different components in my app until I came across this guide. The explanation of NotificationCenter, especially how to use observers and handle userInfo, cleared up so much confusion for me. It’s great to see simple, clear examples that just work.
During this process, I also had to deal with backend configurations, and this Install Ruby on Rails on Debian guide saved me tons of time when setting up server-side dependencies.
Thanks for putting this together—I genuinely love the practical tips shared here!
mtl0w9
j94vc5
I’ve tried several Video Surveillance Software options, and this one stands out from the rest. The AI-powered object detection is incredibly accurate, and the ability to detect people, pets, and even birds is impressive. The free version is perfect for those just starting out, but the professional features are worth the investment. The time-lapse recording and IP camera recorder functionalities are seamless and easy to use. If you’re looking for a comprehensive security solution, this software is definitely worth considering. It’s reliable, feature-rich, and user-friendly.
mf81wo
На этом сайте представлена важная информация о лечении депрессии, в том числе у пожилых людей.
Здесь можно узнать способы диагностики и подходы по улучшению состояния.
http://achards.com/__media__/js/netsoltrademark.php?d=empathycenter.ru%2Farticles%2Famitriptilin-pri-bolyah%2F
Отдельный раздел уделяется возрастным изменениям и их влиянию на эмоциональным состоянием.
Также рассматриваются эффективные терапевтические и психологические методы лечения.
Статьи помогут лучше понять, как правильно подходить к депрессией в пожилом возрасте.
ufzqtn
На этом сайте собрана важная информация о терапии депрессии, в том числе у пожилых людей.
Здесь можно найти методы диагностики и советы по улучшению состояния.
http://capitollightingstores.com/__media__/js/netsoltrademark.php?d=empathycenter.ru%2Farticles%2Felitseya-i-elitseya-ku-tab-preimushchestva%2F
Отдельный раздел уделяется возрастным изменениям и их влиянию на эмоциональным состоянием.
Также рассматриваются современные терапевтические и немедикаментозные методы поддержки.
Материалы помогут разобраться, как справляться с угнетенным состоянием в пожилом возрасте.
jagryv
На этом сайте вы у вас есть возможность купить лайки и подписчиков для Instagram. Это поможет повысить вашу популярность и заинтересовать новую аудиторию. Мы предлагаем моментальное добавление и надежный сервис. Выбирайте удобный пакет и развивайте свой аккаунт легко и просто.
Накрутка лайков Инстаграм быстро
zW8T6kz4zmc
DXR44iDDIY8
На данном сайте АвиаЛавка (AviaLavka) вы можете забронировать выгодные авиабилеты по всему миру.
Мы подбираем лучшие цены от проверенных перевозчиков.
Удобный интерфейс поможет быстро подобрать подходящий рейс.
https://www.avialavka.ru
Интеллектуальный фильтр помогает подобрать оптимальные варианты перелетов.
Бронируйте билеты в пару кликов без переплат.
АвиаЛавка — ваш удобный помощник в путешествиях!
u6uEXKGAFms
Feu8YOkfXus
gfyd7PnHKHs
orgUls3rmNC
xLr5CKyqRam
gkYQd719N2A
JKWP9VKpN5S
X6glEAG1SnC
16eacUYl6tX
5Obw2EA16Gq
m4GAhzHfmvm
bDAXmRz5mm9
MriVSbYs5YY
y2V9DN9rBiO
R6T67EZ9irF
ONe9j5tYgtk
5hFcyp9oBQQ
hXPx8gQNDlk
62MtrAR2qTq
FPahK495Ifd
6mbd5QxPf5H
tOB7bTK15tv
St0FwcoXFg5
astC62QROWj
qLddagYnj5i
Pvs4ds31bjk
nPXO6F4Dd51
5e14CVVKECA
2bB63hdwibT
gHiXuB0n7Rd
WI1phGSAtUO
H2oxqWWN8yR