Junior — Middle
Milliseid muudatusi tuleb süsteemi koodis teha, et toetada push-teavituste töötlemist?
sobes.tech AI
Vastus AI-lt
Push-teavituste töötlemise toetamiseks iOS rakenduses tuleb teha järgmised muudatused:
- Registreerimine push-teavituste saamiseks
Lisada AppDelegate'is kasutaja nõusoleku päring:
import UserNotifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
- Seadme registreerimise töötlemine
Rakendada meetodid seadme tokeni saamiseks:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Saata deviceToken serverile
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Registreerimine ebaõnnestus: \(error)")
}
- Sissetulevate teavituste töötlemine
Rakendada meetodid teavituste töötlemiseks, kui rakendus on taustal või aktiivne:
import UserNotifications
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Töötle teavitust aktiivses rakenduses
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
// Töötle teavitusele klõpsamist
completionHandler()
}
}
- Võimaluste seadistamine
Xcode'is lülitage sisse Push Notifications Signing & Capabilities jaotisest.
Seega saab rakendus vastu võtta ja töödelda serverilt saadetud push-teavitusi.