Để lấy danh sách notification đang hiển thị trong Notification Center (khay trạng thái), dùng UNUserNotificationCenter.current().getDeliveredNotifications().
Lưu ý quan trọng
- Chỉ lấy được notification **của chính app đó** (privacy - không thể đọc notification app khác)
- Trả về các notification **chưa bị user dismiss** (vẫn còn trong Notification Center)
- Không bao gồm notification đã bị user xóa hoặc đã xử lý
Code cơ bản
import UserNotifications
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
print("Số notification đang hiển thị: \(notifications.count)")
for notification in notifications {
let request = notification.request
let content = request.content
print("""
Identifier: \(request.identifier)
Title: \(content.title)
Body: \(content.body)
Badge: \(content.badge ?? 0)
UserInfo: \(content.userInfo)
Date: \(notification.date)
""")
}
}
Ứng dụng thực tế
1. Kiểm tra xem notification cụ thể có đang hiển thị không
func isNotificationDelivered(identifier: String, completion: @escaping (Bool) -> Void) {
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
let exists = notifications.contains { $0.request.identifier == identifier }
completion(exists)
}
}
2. Xóa notification cụ thể khỏi Notification Center
func removeDeliveredNotification(identifier: String) {
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier])
}
3. Xóa tất cả notification của app
func clearAllDeliveredNotifications() {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
4. Cập nhật badge count
func updateBadgeCount(_ count: Int) {
UIApplication.shared.applicationIconBadgeNumber = count
// Hoặc qua notification content
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
let newCount = notifications.count
UIApplication.shared.applicationIconBadgeNumber = newCount
}
}
Notification Content Properties
| Property | Mô tả |
|---|---|
title |
Tiêu đề notification |
subtitle |
Phụ đề |
body |
Nội dung chính |
badge |
Số hiển thị trên icon app |
sound |
Âm thanh |
userInfo |
Dictionary custom data |
attachments |
Media đính kèm (image, video, audio) |
Lưu ý
- Phải import
UserNotificationsframework - Chỉ hoạt động cho notification **local** hoặc **remote** của chính app
- Không thể truy xuất notification đã bị user swipe xóa
- iOS 15+: Có
UNNotificationSettingsđể check authorization status