Junior — Middle
Povedzte nám o vašich skúsenostiach s integráciou a prácou s push notifikáciami v aplikáciách
sobes.tech AI
Odpoveď od AI
V iOS som na prácu s push notifikáciami použil Apple Push Notification Service (APNs). Hlavné kroky zahŕňajú registráciu zariadenia na príjem push notifikácií, získanie device tokenu a jeho odoslanie na server, ktorý následne posiela notifikácie cez APNs.
Na registráciu a spracovanie notifikácií v aplikácii používam metódy z UNUserNotificationCenter a UIApplicationDelegate:
import UserNotifications
// Žiadosť o povolenie od používateľa
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
// Získanie device tokenu
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
// Odoslanie tokenu na server
}
// Spracovanie prijatých notifikácií
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Spracovanie dát notifikácie
completionHandler()
}
Je tiež dôležité poznamenať, že pre správne fungovanie push notifikácií je potrebné nakonfigurovať certifikáty a profily v Apple Developer Center a na serverovej strane.