Sobes.tech
Junior — Middle

Kādus izmaiņas ir nepieciešams veikt sistēmas kodā, lai atbalstītu push paziņojumu apstrādi?

sobes.tech AI

Atbilde no AI

Lai atbalstītu push paziņojumu apstrādi iOS lietotnē, ir jāveic šādas izmaiņas:

  1. Reģistrēšanās saņemt push paziņojumus

Pievienot pieprasījumu lietotāja atļaujai AppDelegate:

import UserNotifications

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    if granted {
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}
  1. Ierīces reģistrācijas apstrāde

Īstenot delegāta metodes device token saņemšanai:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Nosūtīt deviceToken uz serveri
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Reģistrācija neizdevās: \(error)")
}
  1. Ienākošo paziņojumu apstrāde

Īstenot metodes paziņojumu apstrādei, kad lietotne ir fonā un aktīva:

import UserNotifications

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
                                willPresent notification: UNNotification, 
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Apstrādāt paziņojumu aktīvajā lietotnē
        completionHandler([.alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, 
                                didReceive response: UNNotificationResponse, 
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        // Apstrādāt nospiešanu uz paziņojuma
        completionHandler()
    }
}
  1. Iespēju konfigurācija

Xcode ieslēgt Push Notifications Signing & Capabilities sadaļā.

Tādējādi lietotne varēs saņemt un apstrādāt push paziņojumus no servera.