Ответ
1. Настройка проекта и сертификатов
- Добавьте capability "Push Notifications" в Signing & Capabilities
- Создайте/обновите сертификаты в Apple Developer Account:
- Apple Push Notification service SSL
- Key (APNs Auth Key) для более гибкой настройки
2. Запрос разрешения пользователя
import UserNotifications
func requestNotificationAuthorization() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
guard granted else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
3. Регистрация устройства и получение токена
// Успешная регистрация
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print("APNs Token: (token)")
// Отправьте токен на ваш backend-сервер
sendTokenToServer(token)
}
// Ошибка регистрации
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: (error.localizedDescription)")
}
4. Обработка входящих уведомлений
// Для iOS 10+
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
// Уведомление пришло, когда приложение активно
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler:
@escaping (UNNotificationPresentationOptions) -> Void) {
// Определите, как показывать уведомление
completionHandler([.banner, .sound, .badge])
}
// Пользователь тапнул по уведомлению
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Извлеките кастомные данные
if let customData = userInfo["customKey"] as? String {
handleCustomData(customData)
}
// Обработайте action identifier
if response.actionIdentifier == "ACTION_ID" {
handleAction()
}
completionHandler()
}
}
5. Silent Push Notifications (фоновое обновление)
// В AppDelegate
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
guard let aps = userInfo["aps"] as? [String: Any],
aps["content-available"] as? Int == 1 else {
completionHandler(.noData)
return
}
// Выполните фоновую задачу
fetchNewData { success in
completionHandler(success ? .newData : .failed)
}
}
6. Тестирование
- Используйте APNs Sandbox для разработки
- Тестируйте через Xcode (Debug → Simulate Background Fetch)
- Используйте инструменты вроде PushNotifications или NWPusher