UserNotifications – Swift3 – utilizare

1. Import pentru UserNotifications framework si adaugam UNUserNotificationCenterDelegate in AppDelegate.swift
2. Implementare delegatii specifici pentru UNUserNotificationCenterDelegate in ViewController-ul dedicat sau folosind o extensie:
2.1.func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
print("S-a apasat pe notificare, acum ar trebui implementantat ce anume se doreste dupa ce s-a dat click pe notificare")

2.2. func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("S-a primit notificare in foreground, definim aici actiunea care se va efectua in foregorund")

3. Cerere permisiuni de notificare din partea utilizatorului, de asemenea in AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// register user notification
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.alert, .sound]) { (granted, error) in
return true

4. Delegarea actiunilor view-ului curent catre delegatii specifici: userNotificationCenter didReceive: si userNotificationCenter willPresent
UNUserNotificationCenter.current().delegate = self
5. Adaugam Observer care va “reactiona” atunci cand selectorul va “cere” sa efectueze o notificare:
NotificationCenter.default.addObserver(self, selector: #selector(numeMetodaNotificare()), name: NSNotification.Name(rawValue: "identificatorNumeNotificare"), object: nil)
6. Implementare metoda care va genera notificare numeMetodaNotificare()
func numeMetodaNotificare(output name:String)
let notification = UNMutableNotificationContent()
notification.title = NSString.localizedUserNotificationString(forKey: "Request received", arguments: nil)
notification.body = NSString.localizedUserNotificationString(forKey: "Request is: \(name)!", arguments: nil)
notification.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "OneSecond", content: notification, trigger: nil)
let center = UNUserNotificationCenter.current()
print("s-a construit notificarea: \(notification.body)")

Share Button


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.