Sobes.tech
Junior — Middle

Quelles modifications doivent être apportées au code du système pour prendre en charge le traitement des notifications push?

sobes.tech IA

Réponse de l'IA

Pour prendre en charge le traitement des notifications push dans une application iOS, il est nécessaire d'apporter les modifications suivantes :

  1. Enregistrement pour recevoir des notifications push

Ajouter une demande d'autorisation dans AppDelegate :

import UserNotifications

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    if granted {
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}
  1. Traitement de l'enregistrement de l'appareil

Implémenter les méthodes du délégué pour obtenir le token de l'appareil :

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Envoyer deviceToken au serveur
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Échec de l'enregistrement : \(error)")
}
  1. Traitement des notifications entrantes

Implémenter les méthodes pour gérer les notifications lorsque l'application est en arrière-plan ou active :

import UserNotifications

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
                                willPresent notification: UNNotification, 
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Gérer la notification lorsque l'application est active
        completionHandler([.alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, 
                                didReceive response: UNNotificationResponse, 
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        // Gérer l'appui sur la notification
        completionHandler()
    }
}
  1. Configuration des capabilities

Dans Xcode, activer Push Notifications dans la section Signing & Capabilities.

Ainsi, l'application pourra recevoir et traiter les notifications push du serveur.