Junior — Middle
Kokius pakeitimus reikia atlikti sistemos kode, kad būtų galima palaikyti push pranešimų apdorojimą?
sobes.tech AI
Atsakymas iš AI
Norint palaikyti push pranešimų apdorojimą iOS programėlėje, reikia atlikti šiuos pakeitimus:
- Registracija gauti push pranešimus
Pridėti užklausą naudotojo leidimui AppDelegate:
import UserNotifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
- Įrenginio registracijos apdorojimas
Įgyvendinti delegate metodus device token gavimui:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Siųsti deviceToken į serverį
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Registracija nepavyko: \(error)")
}
- Įeinančių pranešimų apdorojimas
Įgyvendinti metodus pranešimų apdorojimui, kai programėlė veikia fone ir aktyviame režime:
import UserNotifications
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Apdoroti pranešimą aktyvioje programėlėje
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
// Apdoroti paspaudimą ant pranešimo
completionHandler()
}
}
- Nustatyti galimybes
Xcode įjungti Push Notifications skyriuje Signing & Capabilities.
Taip programėlė galės gauti ir apdoroti push pranešimus iš serverio.