Saltar a: navegación, buscar

Diferencia entre revisiones de «SDKs:Push:iOS:index»


Línea 1: Línea 1:
 
= CÓMO AGREGAR EL FRAMEWORK PUSHLIB EN iOS =
 
= CÓMO AGREGAR EL FRAMEWORK PUSHLIB EN iOS =
 +
  
  
Línea 15: Línea 16:
  
  
 
+
Para poder enviar notificaciones push lo primero que deberemos hacer es crear los certificados para cada aplicación en [https://developer.apple.com/membercenter/ Apple Developer Center].
Para poder enviar notificaciones push lo primero que deberemos hacer es crear los certificados para cada aplicación en [Apple Developer Center](https://developer.apple.com/membercenter/).
 
  
 
Una vez hayamos accedido nos dirigiremos a la sección <b>Identifiers --> App IDs</b> y pincharemos sobre el simbolo del <b>+</b> parar agregar uno nuevo.
 
Una vez hayamos accedido nos dirigiremos a la sección <b>Identifiers --> App IDs</b> y pincharemos sobre el simbolo del <b>+</b> parar agregar uno nuevo.
Línea 34: Línea 34:
 
exportarlo como <b>.p12 Archivo de Intercambio de Información Personal</b>. Cuando os pregunté por la
 
exportarlo como <b>.p12 Archivo de Intercambio de Información Personal</b>. Cuando os pregunté por la
 
contraseña pincháis a <b>Aceptar y no insertáis ninguna contraseña</b>. Una vez que tenemos el Archivo .p12
 
contraseña pincháis a <b>Aceptar y no insertáis ninguna contraseña</b>. Una vez que tenemos el Archivo .p12
hay que meterlo en el <b>Panel Mobeleader</b>.
+
habrá que configurarlo en nuestro panel.
 +
 
 +
== PASOS A REALIZAR EN NUESTRO PANEL ==
 +
 
  
{{:SDKs:Push:pasos_panel|Pasos a realizar en el Panel Mobeleader}}
+
{{:SDKs:Push:pasos_panel}}
  
{{:SDKs:Push:configurar_android|Configuración Push Android}}
+
{{:SDKs:Push:configurar_ios}}
  
 
== PASOS A REALIZAR PARA LA INSTALACIÓN DEL FRAMEWORK EN LA APLICACIÓN ==
 
== PASOS A REALIZAR PARA LA INSTALACIÓN DEL FRAMEWORK EN LA APLICACIÓN ==
Línea 48: Línea 51:
  
  
En caso de que su proyecto no incluya el archivo <b><i>Podfile</i></b>, incorpórelo. Si nunca ha trabajado con <b>CocoaPods</b> consulte la [documentación ofrecida en su web oficial](https://guides.cocoapods.org/using/using-cocoapods.html), en la que se explica paso a paso cómo instalar <b>CocoaPods</b> y cómo crear, actualizar y trabajar con los archivos <b><i>Podfile</i></b>.
+
En caso de que su proyecto no incluya el archivo <b><i>Podfile</i></b>, incorpórelo. Si nunca ha trabajado con <b>CocoaPods</b> consulte la [https://guides.cocoapods.org/using/using-cocoapods.html documentación ofrecida en su web oficial], en la que se explica paso a paso cómo instalar <b>CocoaPods</b> y cómo crear, actualizar y trabajar con los archivos <b><i>Podfile</i></b>.
  
 
Añada al archivo <b><i>Podfile</i></b> de su proyecto las siguientes dependencias:
 
Añada al archivo <b><i>Podfile</i></b> de su proyecto las siguientes dependencias:
Línea 56: Línea 59:
 
       use_frameworks!
 
       use_frameworks!
 
         pod 'MobeleaderPush'
 
         pod 'MobeleaderPush'
pod 'MobeleaderUtils'
+
        pod 'MobeleaderUtils'
pod 'MobeleaderRegister'
+
        pod 'MobeleaderRegister'
 
     end
 
     end
  
Línea 78: Línea 81:
 
Descargue el <i>framework</i> <b>Push</b>:
 
Descargue el <i>framework</i> <b>Push</b>:
  
* Desde la [página principal de las librerías](http://panel.mobeleader.com/index.php?sec=82):
+
* Desde la [http://panel.mobeleader.com/index.php?sec=82 página principal de las librerías]:
  
  
Línea 90: Línea 93:
 
https://panel.mobeleader.com/ficheros_subidos/librerias/imagenes/referrer/descargar_framework.png
 
https://panel.mobeleader.com/ficheros_subidos/librerias/imagenes/referrer/descargar_framework.png
  
* Directamente desde [aquí](https://repos.mobeleader.com/MobeleaderPush/1.61.XX/MobeleaderPush.zip).
+
* Directamente desde [https://repos.mobeleader.com/MobeleaderPush/1.61.XX/MobeleaderPush.zip aquí].
  
  
Línea 98: Línea 101:
  
  
Una vez configurada correctamente la aplicación en el <b><i>Panel Mobeleader</i></b> con sus respectivos certificados, e instalado el FrameWork, procederemos a realizar las siguientes configuraciones en nuestro proyecto.
+
Una vez configurada correctamente la aplicación en nuestro panel con sus respectivos certificados, e instalado el FrameWork, procederemos a realizar las siguientes configuraciones en nuestro proyecto.
  
 
<b>1.-</b> Desde la sección <b>Captabilities</b> de nuestro "target" principal en el proyecto. Deberemos realizar las siguientes configuraciones:
 
<b>1.-</b> Desde la sección <b>Captabilities</b> de nuestro "target" principal en el proyecto. Deberemos realizar las siguientes configuraciones:
Línea 134: Línea 137:
 
Deberemos reemplazar el código del metodo <b>didReceiveNotificationRequest</b> del archivo <b>NotificationService.m</b>, dicho código será el siguiente:
 
Deberemos reemplazar el código del metodo <b>didReceiveNotificationRequest</b> del archivo <b>NotificationService.m</b>, dicho código será el siguiente:
  
`- (void)didReceiveNotificationRequest:(UNNotificationRequest <i>)request withContentHandler:(void (^)(UNNotificationContent </i> _Nonnull))contentHandler {
+
    - (void)didReceiveNotificationRequest:(UNNotificationRequest <i>)request withContentHandler:(void (^)(UNNotificationContent </i> _Nonnull))contentHandler {
 
      
 
      
    self.contentHandler = contentHandler;
+
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
+
    self.bestAttemptContent = [request.content mutableCopy];
    NSString *attachmentUrlString = [request.content.userInfo objectForKey:@"media-attachment"];
+
    NSString *attachmentUrlString = [request.content.userInfo objectForKey:@"media-attachment"];
 
      
 
      
    if (![attachmentUrlString isKindOfClass:[NSString class]])
+
    if (![attachmentUrlString isKindOfClass:[NSString class]])
        return;
+
        return;
 
    NSURL *url = [NSURL URLWithString:attachmentUrlString];
 
    if (!url)
 
        return;
 
 
      
 
      
     [[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL <i> _Nullable location, NSURLResponse </i> _Nullable response, NSError * _Nullable error) {
+
    NSURL *url = [NSURL URLWithString:attachmentUrlString];
        if (!error) {
+
    if (!url)
            NSString *tempDict = NSTemporaryDirectory();
+
        return;
            NSString *attachmentID = [[[NSUUID UUID] UUIDString] stringByAppendingString:[response.URL.absoluteString lastPathComponent]];
+
      
 +
    [[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL <i> _Nullable location, NSURLResponse </i> _Nullable response, NSError * _Nullable error) {
 +
        if (!error) {
 +
            NSString *tempDict = NSTemporaryDirectory();
 +
            NSString *attachmentID = [[[NSUUID UUID] UUIDString] stringByAppendingString:[response.URL.absoluteString lastPathComponent]];
 
              
 
              
            if(response.suggestedFilename)
+
            if(response.suggestedFilename)
                attachmentID = [[[NSUUID UUID] UUIDString] stringByAppendingString:response.suggestedFilename];
+
                attachmentID = [[[NSUUID UUID] UUIDString] stringByAppendingString:response.suggestedFilename];
 
              
 
              
            NSString *tempFilePath = [tempDict stringByAppendingPathComponent:attachmentID];
+
            NSString *tempFilePath = [tempDict stringByAppendingPathComponent:attachmentID];
 
              
 
              
            if ([[NSFileManager defaultManager] moveItemAtPath:location.path toPath:tempFilePath error:&error]) {
+
            if ([[NSFileManager defaultManager] moveItemAtPath:location.path toPath:tempFilePath error:&error]) {
                UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:attachmentID URL:[NSURL fileURLWithPath:tempFilePath] options:nil error:&error];
+
                UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:attachmentID URL:[NSURL fileURLWithPath:tempFilePath] options:nil error:&error];
 
                  
 
                  
                if (!attachment) {
+
                if (!attachment) {
                    NSLog(@"Create attachment error: %@", error);
+
                    NSLog(@"Create attachment error: %@", error);
                } else {
+
                } else {
                    _bestAttemptContent.attachments = [_bestAttemptContent.attachments arrayByAddingObject:attachment];
+
                    _bestAttemptContent.attachments = [_bestAttemptContent.attachments arrayByAddingObject:attachment];
                }
+
                }
            } else {
+
            } else {
                NSLog(@"Move file error: %@", error);
+
                NSLog(@"Move file error: %@", error);
            }
+
            }
        } else {
+
        } else {
            NSLog(@"Download file error: %@", error);
+
            NSLog(@"Download file error: %@", error);
        }
+
        }
 
          
 
          
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
+
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.contentHandler(self.bestAttemptContent);
+
            self.contentHandler(self.bestAttemptContent);
        }];
+
        }];
    }] resume];
+
    }] resume];
}
+
    }
`
 
De manera que quedará tal que:
 
 
 
https://panel.mobeleader.com/ficheros_subidos/librerias/imagenes/push/RichNotifications_code.png
 
  
 
<b>4.-</b> Para finalizar y poder lanzar el FrameWork, configuraremos los archivos <b>AppDelegate.h</b> y <b>AppDelegate.m</b> de nuestro proyecto:
 
<b>4.-</b> Para finalizar y poder lanzar el FrameWork, configuraremos los archivos <b>AppDelegate.h</b> y <b>AppDelegate.m</b> de nuestro proyecto:
Línea 203: Línea 202:
 
     #[[Push shared] activePushNotificationsInForegroundApp:NO];
 
     #[[Push shared] activePushNotificationsInForegroundApp:NO];
 
     #[[Push shared] activePushNotifications:YES];
 
     #[[Push shared] activePushNotifications:YES];
 +
   
 +
    if([launchOptions count] > 0){
 +
    NSDictionary *remoteNoti = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
 +
    [[Push shared] didReceiveRemoteNotification:remoteNoti];
 +
    }
  
if([launchOptions count] > 0){
 
NSDictionary *remoteNoti = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
 
[[Push shared] didReceiveRemoteNotification:remoteNoti];
 
}
 
  
 
+
Cabe destacar que: <b>"App Hash"</b> deberá ser reemplazado por el hash de la aplicación añadida a nuestro panel; y que la función <b>activePushNotificationsInForegroundApp</b> será opcional. Haciendo uso de ella decidiremos si las notificaciones se mostrarán cuando la aplicación este en primer plano, por defecto no se mostrarán.
Cabe destacar que: <b>"App Hash"</b> deberá ser reemplazado por el hash de la aplicación añadida al <b>Panel Mobeleader</b>; y que la función <b>activePushNotificationsInForegroundApp</b> será opcional. Haciendo uso de ella decidiremos si las notificaciones se mostrarán cuando la aplicación este en primer plano, por defecto no se mostrarán.
 
  
 
<b>4.2.2.- AppDelegate.m:</b> Tambien añadiremos las siguientes funciones al código. Poniendo especial atención en la encargada de recibir notificaciones.
 
<b>4.2.2.- AppDelegate.m:</b> Tambien añadiremos las siguientes funciones al código. Poniendo especial atención en la encargada de recibir notificaciones.
Línea 216: Línea 215:
  
 
     - (void)application:(UIApplication <i>)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData </i>)devToken{
 
     - (void)application:(UIApplication <i>)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData </i>)devToken{
[[Push shared] registerForRemoteNotificationsWithDeviceToken:devToken];
+
        [[Push shared] registerForRemoteNotificationsWithDeviceToken:devToken];
[[Push shared] resetBadge];
+
        [[Push shared] resetBadge];
}
+
    }
 
+
   
 
 
 
 
 
     - (void)application:(UIApplication <i>)application didReceiveRemoteNotification:(NSDictionary </i>)userInfo fetchCompletionHandler(void (^)(UIBackgroundFetchResult result))completionHandler{
 
     - (void)application:(UIApplication <i>)application didReceiveRemoteNotification:(NSDictionary </i>)userInfo fetchCompletionHandler(void (^)(UIBackgroundFetchResult result))completionHandler{
[[Push shared] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
+
        [[Push shared] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
+
    }
  
 
Como se ha indicado previamente, esta segunda función es especial. A partir de iOs 10 tan solo recibira las notificaciones silenciosas o en background. Normalmente, dichas notificaciones son para que las aplicaciones hagan algo por detras sin que el usuario lo detecte, por lo que tendremos dos opciones: <b>1º</b>, procesaremos directamente lo que queramos en dicha función o <b>2º</b>, tal y como se muestra en la imagen, dejaremos que el FrameWork procese la notificación y la recogeremos en el delegate <b>onReceiveNotification</b>, donde la procesaremos. Esto se deja al gusto del desarrollador.
 
Como se ha indicado previamente, esta segunda función es especial. A partir de iOs 10 tan solo recibira las notificaciones silenciosas o en background. Normalmente, dichas notificaciones son para que las aplicaciones hagan algo por detras sin que el usuario lo detecte, por lo que tendremos dos opciones: <b>1º</b>, procesaremos directamente lo que queramos en dicha función o <b>2º</b>, tal y como se muestra en la imagen, dejaremos que el FrameWork procese la notificación y la recogeremos en el delegate <b>onReceiveNotification</b>, donde la procesaremos. Esto se deja al gusto del desarrollador.
Línea 247: Línea 244:
  
 
     -(void)onGetToken:(NSString *)token{}
 
     -(void)onGetToken:(NSString *)token{}
-(void)onRegisterToken:(NSString *)token{}
+
    -(void)onRegisterToken:(NSString *)token{}
-(void)onUpdateToken:(NSString *)token{}
+
    -(void)onUpdateToken:(NSString *)token{}
-(void)onReceiveNotification:(NSDictionary *)notification{}
+
    -(void)onReceiveNotification:(NSDictionary *)notification{}
-(void)onError:(NSString *)error
+
    -(void)onError:(NSString *)error
  
  
 
------------
 
------------

Revisión del 11:22 17 ene 2019

CÓMO AGREGAR EL FRAMEWORK PUSHLIB EN iOS

INTRODUCCIÓN.

Este FrameWork usa el sistema Push de iOs, denominado APNS. Lo primero que realiza es la recogida del Token de cada terminal por aplicación para registrarlo en nuestro sistema. Una vez registrado, se le pueden enviar las notificaciones que desee y que el FrameWork las reciba y las muestre.

VERSIONES SOPORTADAS DE iOS.

El FrameWork Push de Mobeleader soporta versiones de iOs 10 en adelante, en caso de ser menor que iOs 10 no se lanzará.

PASOS A REALIZAR EN APPLE DEVELOPER CENTER.

Para poder enviar notificaciones push lo primero que deberemos hacer es crear los certificados para cada aplicación en Apple Developer Center.

Una vez hayamos accedido nos dirigiremos a la sección Identifiers --> App IDs y pincharemos sobre el simbolo del + parar agregar uno nuevo.

A continuación, debemos crear los certificados, para ello pinchamos en Create Certificate y seguimos las instrucciones que nos indican:

certificados.png

Una vez creados los dos certificados de APNS, tanto el de Development, como el de Production, podremos exportarlos a Mobeleader. Supongamos que queremos usar el de producción directamente, entonces lo que tenemos que hacer es pinchar dos veces en el certificado para que se nos habrá el keychain.

keychain.png

Seleccionamos el certificado y damos en el menú Archivo --> Exportar items y se nos dará la opción de exportarlo como .p12 Archivo de Intercambio de Información Personal. Cuando os pregunté por la contraseña pincháis a Aceptar y no insertáis ninguna contraseña. Una vez que tenemos el Archivo .p12 habrá que configurarlo en nuestro panel.

PASOS A REALIZAR EN NUESTRO PANEL

Para poder configurar las notificaciones Push en una aplicación, debemos de haberla añadido previamente a nuestro panel. Si aún no la tenemos creada, lo haremos desde la sección Mis Aplicaciones del panel, pulsando en Crear Aplicación.


panel_1.png


Rellenamos los datos necesarios y enviamos el formulario.


panel_2.png


Una vez creada la aplicación, iremos a la sección Mis Aplicaciones del panel y pulsaremos Añadir app a push.


panel_3.png

Desde aquí configuraremos nuestra aplicación ( NOTA: Los certificados que hemos de exportar han de ser los mismos que hemos generado en el Apple Developer Center, coincidiendo tambien el tipo de certificado [ produccion / desarrollo ])

anadir_certificados_ios.png


Una vez creada la app, solo nos queda configurar nuestro proyecto en el XCODE para poder comenzar con las notificaciones.

AppPushCreada_5.png

PASOS A REALIZAR PARA LA INSTALACIÓN DEL FRAMEWORK EN LA APLICACIÓN

Existen dos maneras de instalar el FrameWork Push: a través de CocoaPods o descargándolo directamente. Recomendamos hacerlo a través de la primera opción. Push incorpora dos frameworks auxiliares, RegisterLib y UtilsLib.

INSTALACIÓN CON COCOAPODS:

En caso de que su proyecto no incluya el archivo Podfile, incorpórelo. Si nunca ha trabajado con CocoaPods consulte la documentación ofrecida en su web oficial, en la que se explica paso a paso cómo instalar CocoaPods y cómo crear, actualizar y trabajar con los archivos Podfile.

Añada al archivo Podfile de su proyecto las siguientes dependencias:


   target 'NameTarget' do
      use_frameworks!
       pod 'MobeleaderPush'
       pod 'MobeleaderUtils'
       pod 'MobeleaderRegister'
   end


Cabe destacar que NameTarget deberá ser reemplazado por el nombre real del target de la aplicación en la que se quiere añadir el framework.

Una vez creado y configurado el archivo haremos uso del siguiente comando desde el terminal sobre la ruta en la que se encuentra dicho archivo.

   $ pod install --repo-update

Y veremos como se crea un proyecto tal que el siguiente:

Proyecto_nc_ios_8.png

Deberemos abrir el proyecto desde dicho archivo para que pueda usar el framework correctamente.

INSTALACIÓN MANUAL DEL FRAMEWORK:

Descargue el framework Push:


descargar_ios_push_general.png


descargar_ios_push_especifica_1.png

descargar_framework.png

  • Directamente desde aquí.


Una vez descargado el framework, descomprímalo e instálelo en su proyecto.

LANZAMIENTO

Una vez configurada correctamente la aplicación en nuestro panel con sus respectivos certificados, e instalado el FrameWork, procederemos a realizar las siguientes configuraciones en nuestro proyecto.

1.- Desde la sección Captabilities de nuestro "target" principal en el proyecto. Deberemos realizar las siguientes configuraciones:

captabilities_ios.png

1.1.- Activaremos las Notificaciones Push.

active_push_ios.png

1.2- Activaremos el Background Mode, de manera que nos deje activar las notificaciones remotas tal que se muestra en la siguiente imagen.

background_mode_ios_push.png

2.- Desde la sección Info de nuestro "target" principal en el proyecto. Deberemos añadir la siguiente key con el fin de añadir soporte a conexiones que no sean https ( obligatorio a partir de iOs 9 ):

seccion_info.png

info_plist_ios.png

3.- El FrameWork Push esta dotado de la capacidad de mostrar notificaciones enriquecidas; es decir, es capaz de mostrar notificaciones con contenido como imagenes, videos y audios. Para ello deberemos añadir a nuestro target principal una nueva extensión siguiendo los pasos expuestos a continuación:

add_ns_1.png

add_ns_2.png

RichNotifications_edited.png

Por motivos de seguridad y privacidad en ésta última imagen se han protegido los datos relacionados con el desarollador y la compañia desarrolladora. Cabe destacar, que en el apartado Embed in Application deberemos seleccionador el target de la aplicación configurada previamente en los pasos 1 y 2 de éste mismo apartado.

Al añadir la extensión se generará algo tal que lo siguiente en nuestro proyecto:

RichNotifications_folders.png

Deberemos reemplazar el código del metodo didReceiveNotificationRequest del archivo NotificationService.m, dicho código será el siguiente:

   - (void)didReceiveNotificationRequest:(UNNotificationRequest )request withContentHandler:(void (^)(UNNotificationContent  _Nonnull))contentHandler {
   
   	self.contentHandler = contentHandler;
   	self.bestAttemptContent = [request.content mutableCopy];
   	NSString *attachmentUrlString = [request.content.userInfo objectForKey:@"media-attachment"];
   
   	if (![attachmentUrlString isKindOfClass:[NSString class]])
       		return;
   
   	NSURL *url = [NSURL URLWithString:attachmentUrlString];
   	if (!url)
       		return;
   
   	[[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL  _Nullable location, NSURLResponse  _Nullable response, NSError * _Nullable error) {
       		if (!error) {
           		NSString *tempDict = NSTemporaryDirectory();
           		NSString *attachmentID = [[[NSUUID UUID] UUIDString] stringByAppendingString:[response.URL.absoluteString lastPathComponent]];
           
           		if(response.suggestedFilename)
               		attachmentID = [[[NSUUID UUID] UUIDString] stringByAppendingString:response.suggestedFilename];
           
           		NSString *tempFilePath = [tempDict stringByAppendingPathComponent:attachmentID];
           
           		if ([[NSFileManager defaultManager] moveItemAtPath:location.path toPath:tempFilePath error:&error]) {
               			UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:attachmentID URL:[NSURL fileURLWithPath:tempFilePath] options:nil error:&error];
               
               			if (!attachment) {
                   			NSLog(@"Create attachment error: %@", error);
               			} else {
                   			_bestAttemptContent.attachments = [_bestAttemptContent.attachments arrayByAddingObject:attachment];
               			}
           		} else {
               		NSLog(@"Move file error: %@", error);
           		}
       		} else {
           		NSLog(@"Download file error: %@", error);
       		}
       
       		[[NSOperationQueue mainQueue] addOperationWithBlock:^{
           		self.contentHandler(self.bestAttemptContent);
       		}];
   	}] resume];
   }

4.- Para finalizar y poder lanzar el FrameWork, configuraremos los archivos AppDelegate.h y AppDelegate.m de nuestro proyecto:

4.1.- AppDelegate.h: Añadiremos el siguiente import, de manera que podamos añadir su delegate al interface tal y como se muestra en las imagenes.


   #Import <UserNotifications/UserNotifications.h>


   @interface AppDelegate : UIResponder <UNUserNotificationCenterDelegate>


4.2.- AppDelegate.m: Comenzaremos importando el FrameWork Push.

   #Import <MobeleaderPush/MobeleaderPush.h>

4.2.1.- AppDelegate.m: A continuación en la función didFinishLaunchingWithOptions introduciremos lo siguiente.

   #[[Push shared] setAppHash:@"App Hash"];
   #[[Push shared] setDelegate:self];
   #[[Push shared] activePushNotificationsInForegroundApp:NO];
   #[[Push shared] activePushNotifications:YES];
   
   if([launchOptions count] > 0){
   	NSDictionary *remoteNoti = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
   	[[Push shared] didReceiveRemoteNotification:remoteNoti];
   }


Cabe destacar que: "App Hash" deberá ser reemplazado por el hash de la aplicación añadida a nuestro panel; y que la función activePushNotificationsInForegroundApp será opcional. Haciendo uso de ella decidiremos si las notificaciones se mostrarán cuando la aplicación este en primer plano, por defecto no se mostrarán.

4.2.2.- AppDelegate.m: Tambien añadiremos las siguientes funciones al código. Poniendo especial atención en la encargada de recibir notificaciones.


   - (void)application:(UIApplication )application didRegisterForRemoteNotificationsWithDeviceToken:(NSData )devToken{
       [[Push shared] registerForRemoteNotificationsWithDeviceToken:devToken];
       [[Push shared] resetBadge];
   }
   
   - (void)application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo fetchCompletionHandler(void (^)(UIBackgroundFetchResult result))completionHandler{
       [[Push shared] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
   }

Como se ha indicado previamente, esta segunda función es especial. A partir de iOs 10 tan solo recibira las notificaciones silenciosas o en background. Normalmente, dichas notificaciones son para que las aplicaciones hagan algo por detras sin que el usuario lo detecte, por lo que tendremos dos opciones: , procesaremos directamente lo que queramos en dicha función o , tal y como se muestra en la imagen, dejaremos que el FrameWork procese la notificación y la recogeremos en el delegate onReceiveNotification, donde la procesaremos. Esto se deja al gusto del desarrollador.


DELEGATES

El FrameWork Push esta dotado de varios delegates opcionales mediante los cuales se podrá controlar lo que esta sucediendo en cada momento. Dichos delegates son los siguientes:

  • onGetToken:(NSString \*) token: Notifica cuando la librería ha recibido el token (Para rescatar este token y poder hacer pruebas con el) y devuelve el token registrado en el argumento NSString.
  • onRegisterToken:(NSString \*) token: Notifica cuando la librería ha registrado el token y devuelve el token registrado en el argumento NSString.
  • onUpdateToken:(NSString \*) token: Notifica cuando la librería ha actualizado el token y devuelve el token actualizado en el argumento NSString.
  • onReceiveNotification:(NSDictionary \*) dictionary: Notifica cuando la librería ha recibido una notificación y devuelve la notificación en el argumento NSDictionary.
  • onError:(NSString \*) error: Notifica cuando la librería ha tenido algún error, y devuelve la descripción del error en el argumento NSString.


   -(void)onGetToken:(NSString *)token{}
   -(void)onRegisterToken:(NSString *)token{}
   -(void)onUpdateToken:(NSString *)token{}
   -(void)onReceiveNotification:(NSDictionary *)notification{}
   -(void)onError:(NSString *)error