notificaciones ios swift apple-push-notifications

ios - Cómo configurar notificaciones push en Swift



notificaciones push swift (10)

Swift 4

Creo que esta es la forma correcta de configurar en iOS 8 y superior .

Active Push Notifications en la pestaña Capabilities

Importar UserNotifications

import UserNotifications

Modificar didFinishLaunchingWithOptions

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] { // If your app wasn’t running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions let aps = notification["aps"] as! [String: AnyObject] UIApplication.shared.applicationIconBadgeNumber = 0 } registerForPushNotifications() return true }

Es extremadamente importante llamar a registerUserNotificationSettings(_:) cada vez que se inicia la aplicación. Esto se debe a que el usuario puede, en cualquier momento, acceder a la aplicación Configuración y cambiar los permisos de notificación. application(_:didRegisterUserNotificationSettings:) siempre le proporcionará los permisos que el usuario ha permitido actualmente para su aplicación.

Copie y pegue esta extensión de AppDelegate

// Push Notificaion extension AppDelegate { func registerForPushNotifications() { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] (granted, error) in print("Permission granted: /(granted)") guard granted else { print("Please enable /"Notifications/" from App Settings.") self?.showPermissionAlert() return } self?.getNotificationSettings() } } else { let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) UIApplication.shared.registerForRemoteNotifications() } } @available(iOS 10.0, *) func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in print("Notification settings: /(settings)") guard settings.authorizationStatus == .authorized else { return } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenParts = deviceToken.map { data -> String in return String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Device Token: /(token)") //UserDefaults.standard.set(token, forKey: DEVICE_TOKEN) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register: /(error)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { // If your app was running and in the foreground // Or // If your app was running or suspended in the background and the user brings it to the foreground by tapping the push notification print("didReceiveRemoteNotification /(userInfo)") guard let dict = userInfo["aps"] as? [String: Any], let msg = dict ["alert"] as? String else { print("Notification Parsing Error") return } } func showPermissionAlert() { let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in self?.gotoAppSettings() } let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) alert.addAction(settingsAction) alert.addAction(cancelAction) DispatchQueue.main.async { self.window?.rootViewController?.present(alert, animated: true, completion: nil) } } private func gotoAppSettings() { guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.openURL(settingsUrl) } } }

Consulte: Tutorial de Notificaciones Push: Primeros pasos

Estoy tratando de configurar un sistema de notificación push para mi aplicación. Tengo un servidor y una licencia de desarrollador para configurar el servicio de notificación push.

Actualmente estoy ejecutando mi aplicación en Swift. Me gustaría poder enviar las notificaciones de forma remota desde mi servidor. ¿Cómo puedo hacer esto?


Gracias por las respuestas anteriores. Xcode ha realizado algunos cambios y aquí está el código de SWIFT 2 que pasa la comprobación de código de XCode 7 y es compatible con iOS 7 y versiones posteriores:

if #available(iOS 8.0, *) { let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() } else { let settings = UIRemoteNotificationType.Alert.union(UIRemoteNotificationType.Badge).union(UIRemoteNotificationType.Sound) UIApplication.sharedApplication().registerForRemoteNotificationTypes(settings) }


Para admitir iOS 8 y versiones anteriores, usa esto:

// Register for Push Notitications, if running iOS 8 if application.respondsToSelector("registerUserNotificationSettings:") { let types:UIUserNotificationType = (.Alert | .Badge | .Sound) let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { // Register for Push Notifications before iOS 8 application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound) }


Para registrarse y recibir notificaciones push a través del Servicio Push de Apple, debe llamar al método registerForRemoteNotifications() de UIApplication .

Si el registro tiene éxito, la aplicación llama a la aplicación del objeto delegado de su application:didRegisterForRemoteNotificationsWithDeviceToken: método application:didRegisterForRemoteNotificationsWithDeviceToken: y le pasa un token del dispositivo.

Debe pasar este token al servidor que usa para generar notificaciones automáticas para el dispositivo. Si el registro falla, la aplicación llama a la aplicación del delegado de su application:didFailToRegisterForRemoteNotificationsWithError: método application:didFailToRegisterForRemoteNotificationsWithError: lugar.

Eche un vistazo a la Guía de programación local y de notificación de inserción .


Puede enviar notificaciones utilizando el siguiente fragmento de código:

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){ //OK }else{ //KO }


Si bien la respuesta es buena para manejar notificaciones automáticas, aún así creo que comparto el caso completo integrado de una vez para facilitar:

Para registrar la aplicación para APNS, (Incluya el siguiente código en el método didFinishLaunchingWithOptions dentro de AppDelegate.swift)

IOS 9

var settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert|UIUserNotificationType.Sound, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications()

Después de IOS 10

Marco de UserNotifications introducido:

Importe el marco UserNotifications y agregue UNUserNotificationCenterDelegate en AppDelegate.swift

Para registrar la solicitud de APNS

let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } application.registerForRemoteNotifications()

Esto llamará al siguiente método delegado

func application(application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { //send this device token to server } //Called if unable to register for APNS. func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { println(error) }

Al recibir la notificación siguiente, el delegado llamará a:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { println("Recived: /(userInfo)") //Parsing userinfo: var temp : NSDictionary = userInfo if let info = userInfo["aps"] as? Dictionary<String, AnyObject> { var alertMsg = info["alert"] as! String var alert: UIAlertView! alert = UIAlertView(title: "", message: alertMsg, delegate: nil, cancelButtonTitle: "OK") alert.show() } }

Para identificar el permiso dado, podemos usar:

UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in switch setttings.soundSetting{ case .enabled: print("enabled sound") case .disabled: print("not allowed notifications") case .notSupported: print("something went wrong here") } }

Entonces la lista de verificación de APNS:

  1. Crear AppId permitido con notificación push
  2. Crear certificado SSL con un certificado válido y una identificación de la aplicación
  3. Cree el perfil de Aprovisionamiento con el mismo certificado y asegúrese de agregar el dispositivo en caso de espacio aislado (aprovisionamiento de desarrollo). Nota: Eso será bueno si crea el perfil de Aprovisionamiento después del Certificado SSL.

Con Código:

  1. Aplicación de registro para notificación push
  2. Manejar el método didRegisterForRemoteNotificationsWithDeviceToken
  3. Establecer objetivos> Capacidad> modos de fondo> Notificación remota
  4. Manejar didReceiveRemoteNotification

Utilizo este recorte de código en AppDelegate.swift:

let pushType = UIUserNotificationType.alert.union(.badge).union(.sound) let pushSettings = UIUserNotificationSettings(types: pushType , categories: nil) application.registerUserNotificationSettings(pushSettings) application.registerForRemoteNotifications()


registerForRemoteNotification() se ha eliminado de ios8.

Entonces deberías usar UIUserNotification

EJEMPLO DE CÓDIGO:

var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound; var setting = UIUserNotificationSettings(forTypes: type, categories: nil); UIApplication.sharedApplication().registerUserNotificationSettings(setting); UIApplication.sharedApplication().registerForRemoteNotifications();

Espero que esto te ayudará.


Swift 2:

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications()


Swift 3:

let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } UIApplication.shared.registerForRemoteNotifications()

Asegúrese de importar UserNotifications en la parte superior de su controlador de vista.

import UserNotifications