Swift - код push-уведомления
Чтобы зарегистрировать приложение для apns
//MARK:- Register for push notification -
func setupPushNotification() {
if #available(iOS 10, *) {
UIApplication.shared.registerForRemoteNotifications()
let center = UNUserNotificationCenter.current()
center.delegate = self //DID NOT WORK WHEN self WAS MyOtherDelegateClass()
center.requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
// Enable or disable features based on authorization.
if granted {
// update application settings
}
}
}
else {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
}
//Call from did become active
func applicationDidBecomeActive(_ application: UIApplication) {
self.setupPushNotification()
}
Это вызовет следующий метод делегата
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("$$$$$$$ Device Token = %@", deviceTokenString)
//send device token to server
}
//Called if device not register
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NSLog("Error Push **********")
print("i am not available in simulator \(error)")
}
При получении Push-уведомление после вызова метода
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//Handle push notification response
NSLog("Notification Response = %@", userInfo)
}