Sobes.tech
Junior — Middle

Pastāstiet mums par savu pieredzi ar paziņojumu integrēšanu un darbu ar push paziņojumiem lietotnēs

sobes.tech AI

Atbilde no AI

iOS, lai darbotos ar push paziņojumiem, es izmantoju Apple Push Notification Service (APNs). Galvenie soļi ir ierīces reģistrēšana, lai saņemtu push paziņojumus, iegūt ierīces tokenu un nosūtīt to uz serveri, kas pēc tam sūta paziņojumus caur APNs.

Lai reģistrētu un pārvaldītu paziņojumus lietotnē, es izmantoju UNUserNotificationCenter un UIApplicationDelegate metodes:

import UserNotifications

// Pieprasīt atļauju no lietotāja
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    if granted {
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

// Iegūt ierīces 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)")
    // Nosūtīt tokenu uz serveri
}

// Apstrādāt saņemtos paziņojumus
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Apstrādāt paziņojuma datus
    completionHandler()
}

Ir arī svarīgi atzīmēt, ka, lai push paziņojumi darbotos pareizi, ir jākonfigurē sertifikāti un profili Apple Developer Center un servera pusē.