rust_macios/user_notifications/
un_user_notification_center.rs

1use block::{ConcreteBlock, IntoConcreteBlock};
2use objc::{msg_send, sel, sel_impl};
3
4use crate::{
5    foundation::{Int, NSArray, NSError, NSSet, NSString},
6    object,
7    objective_c_runtime::{
8        id,
9        macros::interface_impl,
10        traits::{FromId, PNSObject},
11    },
12    utils::to_bool,
13};
14
15use super::{
16    UNNotification, UNNotificationCategory, UNNotificationRequest, UNNotificationSettings,
17};
18
19object! {
20    /// The central object for managing notification-related activities for your app or app extension.
21    unsafe pub struct UNUserNotificationCenter;
22}
23
24/// Pointer for [`UNUserNotificationCenter`]
25pub static UNUSER_NOTIFICATION_CENTER_PTR: &str = "rstUNUserNotificationCenterPtr";
26
27/// Options that determine the authorized features of local and remote notifications.
28#[repr(u64)]
29#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
30pub enum UNAuthorizationOptions {
31    /// No authorization options.
32    None = 0,
33    /// The ability to update the app’s badge.
34    Badge = (1 << 0),
35    /// The ability to play sounds.
36    Sound = (1 << 1),
37    /// The ability to display alerts.
38    Alert = (1 << 2),
39    /// The ability to display notifications in a CarPlay environment.
40    CarPlay = (1 << 3),
41    /// The ability to play sounds for critical alerts.
42    #[cfg(target_os = "ios")]
43    CriticalAlert = (1 << 4),
44    /// An option indicating the system should display a button for in-app notification settings.
45    #[cfg(target_os = "ios")]
46    ProvidesAppNotificationSettings = (1 << 5),
47    /// The ability to post noninterrupting notifications provisionally to the Notification Center.
48    #[cfg(target_os = "ios")]
49    Provisional = (1 << 6),
50    /// The ability for Siri to automatically read out messages over AirPods.
51    #[deprecated]
52    #[cfg(target_os = "ios")]
53    Announcement = (1 << 7),
54    ///
55    #[deprecated]
56    #[cfg(any(target_os = "ios", target_os = "macos"))]
57    TimeSensitive = (1 << 8),
58}
59
60/// Constants that identify notification errors.
61#[repr(i64)]
62#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
63pub enum UNErrorCode {
64    /// Notifications aren’t allowed.
65    NotificationsNotAllowed = 1,
66    /// The URL for an attachment was invalid.
67    AttachmentInvalidUrl = 100,
68    /// The file type of an attachment isn’t supported.
69    AttachmentUnrecognizedType,
70    /// An attachment is too large.
71    AttachmentInvalidFileSize,
72    /// The specified attachment isn’t in the system data store.
73    AttachmentNotInDataStore,
74    /// An error occurred when trying to move an attachment to the system data store.
75    AttachmentMoveIntoDataStoreFailed,
76    /// The file for an attachment is corrupt.
77    AttachmentCorrupt,
78    /// The notification doesn’t have an associated date, but should.
79    NotificationInvalidNoDate = 1400,
80    /// The notification has no user-facing content, but should.
81    NotificationInvalidNoContent,
82    ///
83    ContentProvidingObjectNotAllowed = 1500,
84    ///
85    ContentProvidingInvalid = 1501,
86}
87
88#[interface_impl(NSObject)]
89impl UNUserNotificationCenter {
90    /* Managing the notification center
91     */
92
93    /// Returns your app’s notification center.
94    #[method]
95    pub fn current_notification_center() -> UNUserNotificationCenter
96    where
97        Self: Sized + FromId,
98    {
99        unsafe { msg_send![Self::m_class(), currentNotificationCenter] }
100    }
101
102    /// Retrieves the authorization and feature-related settings for your app.
103    #[method]
104    pub fn get_notification_settings_with_completion_handler<F>(&self, completion_handler: F)
105    where
106        F: IntoConcreteBlock<(UNNotificationSettings,), Ret = ()> + 'static,
107    {
108        let block = ConcreteBlock::new(completion_handler);
109        let block = block.copy();
110
111        unsafe {
112            msg_send![
113                self.m_self(),
114                getNotificationSettingsWithCompletionHandler: block
115            ]
116        }
117    }
118
119    /// Updates the badge count for your app’s icon.
120    #[method]
121    pub fn set_badge_count_with_completion_handler<F>(
122        &mut self,
123        new_badge_count: Int,
124        completion_handler: F,
125    ) where
126        F: IntoConcreteBlock<(NSError,), Ret = ()> + 'static,
127    {
128        let block = ConcreteBlock::new(completion_handler);
129        let block = block.copy();
130        unsafe {
131            msg_send![self.m_self(), setBadgeCount: new_badge_count withCompletionHandler: block]
132        }
133    }
134
135    /* Requesting authorization
136     */
137
138    /// Requests the user’s authorization to allow local and remote notifications for your app.
139    #[method]
140    pub fn request_authorization_with_options_completion_handler<F>(
141        &mut self,
142        options: &[UNAuthorizationOptions],
143        completion_handler: F,
144    ) where
145        F: IntoConcreteBlock<(bool, Option<NSError>), Ret = ()> + 'static,
146    {
147        let options = options
148            .iter()
149            .fold(0u64, |init, option| init | *option as u64);
150        let block = ConcreteBlock::new(completion_handler);
151        let block = block.copy();
152
153        unsafe {
154            msg_send![self.m_self(), requestAuthorizationWithOptions:options completionHandler: block]
155        }
156    }
157
158    /* Processing received notifications
159     */
160
161    /// The delegate of the notification center.
162    #[property]
163    pub fn delegate(&self) -> Option<id> {
164        unsafe {
165            let ptr: id = msg_send![self.m_self(), delegate];
166
167            if ptr.is_null() {
168                None
169            } else {
170                Some(ptr)
171            }
172        }
173    }
174
175    /// Sets the delegate of the notification center.
176    ///
177    /// # Arguments
178    ///
179    /// * `delegate` - The delegate to use.
180    #[property]
181    pub fn set_delegate(&self, delegate: id) {
182        unsafe { msg_send![self.m_self(), setDelegate: delegate] }
183    }
184
185    /// A Boolean value that indicates whether the device supports notification content extensions.
186    #[property]
187    pub fn supports_content_extensions(&self) -> bool {
188        unsafe { to_bool(msg_send![self.m_self(), supportsContentExtensions]) }
189    }
190
191    /* Scheduling notifications
192     */
193
194    /// Schedules the delivery of a local notification.
195    #[method]
196    pub fn add_notification_request_with_completion_handler<F>(
197        &mut self,
198        request: &UNNotificationRequest,
199        completion_handler: F,
200    ) where
201        F: IntoConcreteBlock<(NSError,), Ret = ()> + 'static,
202    {
203        let block = ConcreteBlock::new(completion_handler);
204        let block = block.copy();
205
206        unsafe {
207            msg_send![self.m_self(), addNotificationRequest: request.m_self() withCompletionHandler: block]
208        }
209    }
210
211    /// Fetches all of your app’s local notifications that are pending delivery.
212    #[method]
213    pub fn get_pending_notification_requests_with_completion_handler<F>(
214        &self,
215        completion_handler: F,
216    ) where
217        F: IntoConcreteBlock<(NSArray<UNNotificationRequest>,)>,
218    {
219        unsafe {
220            msg_send![
221                self.m_self(),
222                getPendingNotificationRequestsWithCompletionHandler: completion_handler
223            ]
224        }
225    }
226
227    /// Removes your app’s local notifications that are pending and match the specified identifiers.
228    #[method]
229    pub fn remove_pending_notification_requests_with_identifiers(
230        &mut self,
231        identifiers: &NSArray<NSString>,
232    ) {
233        unsafe {
234            msg_send![
235                self.m_self(),
236                removePendingNotificationRequestsWithIdentifiers: identifiers.m_self()
237            ]
238        }
239    }
240
241    /// Removes all of your app’s pending local notifications.
242    #[method]
243    pub fn remove_all_pending_notification_requests(&mut self) {
244        unsafe { msg_send![self.m_self(), removeAllPendingNotificationRequests] }
245    }
246
247    /*  Removing delivered notifications*/
248
249    /// Fetches all of your app’s delivered notifications that are still present in Notification Center.
250    #[method]
251    pub fn get_delivered_notifications_with_completion_handler<F>(&self, completion_handler: F)
252    where
253        F: IntoConcreteBlock<(NSArray<UNNotification>,)>,
254    {
255        unsafe {
256            msg_send![
257                self.m_self(),
258                getDeliveredNotificationsWithCompletionHandler: completion_handler
259            ]
260        }
261    }
262
263    /// Removes your app’s notifications from Notification Center that match the specified identifiers.
264    #[method]
265    pub fn remove_delivered_notifications_with_identifiers(
266        &mut self,
267        identifiers: &NSArray<NSString>,
268    ) {
269        unsafe {
270            msg_send![
271                self.m_self(),
272                removeDeliveredNotificationsWithIdentifiers: identifiers.m_self()
273            ]
274        }
275    }
276
277    /// Removes all of your app’s delivered notifications from Notification Center.
278    #[method]
279    pub fn remove_all_delivered_notifications(&mut self) {
280        unsafe { msg_send![self.m_self(), removeAllDeliveredNotifications] }
281    }
282
283    /*  Managing notification categories */
284
285    /// Registers the notification categories that your app supports.
286    #[method]
287    pub fn set_notification_categories(&mut self, categories: &NSSet<UNNotificationCategory>) {
288        unsafe { msg_send![self.m_self(), setNotificationCategories: categories.m_self()] }
289    }
290
291    /// Fetches your app’s registered notification categories.
292    #[method]
293    pub fn get_notification_categories_with_completion_handler<F>(&self, completion_handler: F)
294    where
295        F: IntoConcreteBlock<(NSSet<UNNotificationCategory>,)> + 'static,
296    {
297        unsafe {
298            msg_send![
299                self.m_self(),
300                getNotificationCategoriesWithCompletionHandler: completion_handler
301            ]
302        }
303    }
304}