¿Cómo extiendo el protocolo UNUserNotificationCenterDelegate en AppDelegate?
Estoy trabajando en una aplicación React Native que utiliza dos bibliotecas diferentes para manejar notificaciones locales (react-native-community/push-notification-ios
) y notificaciones de empuje remoto (Leanplum). El SDK de Leanplum utiliza el asado. Desafortunadamente, incluso cuando desactivar el arrastre, la configuración recomendada para mostrar notificaciones de primer plano está impidiendo que las notificaciones remotas sean manejadas correctamente.
Recibí un comentario del equipo de soporte para la notificación remota SDK
su implementación aquí en el nivel local está interfiriendo con el Leanplum swizzle. ¿Puede implementar el protocolo de delegado de notificación de usuario, que se extiende en la clase de delegado de aplicación? En las implementaciones iOS esto permite las dos lógicas (LP y local) de forma automática y suave. nuestra aplicación recomendada es que el AppDelegate extienda el protocolo UNUserNotificationCenterDelegate, especialmente si desea mantener la aplicación de impulso local
Aunque estoy haciendo todo lo posible para aprender Objetivo-C tan rápido como pueda, no soy un desarrollador nativo de iOS, y no estoy seguro de cómo seguir este consejo. He leído muchas preguntas sobre cómo establecer notificaciones de empuje, pero todos recomiendan la siguiente configuración, y no he podido encontrar ninguna que se ocupe de este caso de gestión de notificación de primer plano interfiriendo con otra biblioteca.
¿Cómo extiendo el UNUserNotificationCenterDelegate
protocolo en el AppDelegate para manejar notificaciones de primer plano de una manera que no interfiera con la biblioteca de notificación remota?
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[...]
// Define UNUserNotificationCenter
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self; // <-- interferes with the remote notification SDK
[RNSplashScreen show];
return YES;
}
[...]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
// Needs to be called if swizzling is disabled in Info.plist otherwise it won’t affect SDK if swizzling is enabled.
[Leanplum didReceiveRemoteNotification:userInfo
fetchCompletionHandler:completionHandler];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
// Needs to be called if swizzling is disabled in Info.plist otherwise it won’t affect SDK if swizzling is enabled.
[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
[Leanplum didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
// Needs to be called if swizzling is disabled in Info.plist otherwise it won’t affect SDK if swizzling is enabled.
[Leanplum didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
[RNCPushNotificationIOS didReceiveNotificationResponse:response];
}
//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
Editar: Los métodos de notificación remota se copian directamente de la Leanplum docs.
Cuando quito este código de AppDelegate.m, todo funciona según lo esperado para las notificaciones remotas. Es sólo cuando agrego estas piezas para presentar notificaciones preliminares que noto problemas con las notificaciones remotas de Leanplum, como las acciones abiertas que no se ejecutan.
// Define UNUserNotificationCenter
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self; // <-- interferes with the remote notification SDK
...
//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
Pregunta hecha hace 3 años, 4 meses, 27 días - Por scriptsculptor52b5
3 Respuestas:
-
Me enfrenté al mismo problema, pero descubrí que un código profundo de Leanplum ya no se llamaba cuando desactivaba el molido.
Añadir esto en la parte superior de su archivo
#import
Reemplazamiento
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge); }
Con esto:
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { [[LPPushNotificationsManager sharedManager].handler willPresentNotification:notification withCompletionHandler:completionHandler]; }
Respondida el Dec 18, 2020 a las 18:18 - por techtactician
Votos positivos: 0 | Votos negativos: 0 -
Para extender el protocolo
UNUserNotificationCenterDelegate
en elAppDelegate
, debes seguir los siguientes pasos:- Añadir la declaración del protocolo `UNUserNotificationCenterDelegate` en la clase `AppDelegate.h`:
objective-c @interface AppDelegate : UIResponder
- Implementar los métodos del protocolo `UNUserNotificationCenterDelegate` en la clase `AppDelegate.m`. Aquí tienes un ejemplo de cómo implementar los métodos necesarios:
objective-c // Método llamado cuando se recibe una respuesta a una notificación
- (void)userNotificationCenter:(UNUserNotificationCenter )center didReceiveNotificationResponse:(UNNotificationResponse )response withCompletionHandler:(void (^)(void))completionHandler {
- (void)userNotificationCenter:(UNUserNotificationCenter )center willPresentNotification:(UNNotification )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
- Ahora, en el método `didFinishLaunchingWithOptions` de tu `AppDelegate.m`, asegúrate de definir el `UNUserNotificationCenter` y establecer el `delegate` correctamente:
objective-c
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions
Con estos cambios, habrás extendido el protocolo
UNUserNotificationCenterDelegate
en tuAppDelegate
y podrás manejar las notificaciones locales de una manera que no interfiera con la biblioteca de notificaciones remotas.Respondida el Dec 19, 2020 a las 18:19 - por Gpt
Votos positivos: 0 | Votos negativos: 0 -
Claro, aquí tienes los pasos para extender el protocolo
UNUserNotificationCenterDelegate
enAppDelegate
para manejar notificaciones de primer plano sin interferir con la biblioteca de notificaciones remotas:1. Importar el encabezado UNUserNotificationCenterDelegate:
objective-c
import 2. Declarar la conformidad con el protocolo UNUserNotificationCenterDelegate:
objective-c @interface AppDelegate : UIResponder
3. Sintetizar las propiedades de notificación:
objective-c @property (nonatomic, strong) UNUserNotificationCenter userNotificationCenter;
4. Implementar los métodos de delegación:
objective-c
- (void)userNotificationCenter:(UNUserNotificationCenter )center willPresentNotification:(UNNotification )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
- (void)userNotificationCenter:(UNUserNotificationCenter )center didReceiveNotificationResponse:(UNNotificationResponse )response withCompletionHandler:(void (^)(void))completionHandler {
5. Configurar el delegado del centro de notificaciones:
objective-c
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions {
6. Reemplazar los métodos de notificación local con los métodos de delegación:
En lugar de utilizar los métodos
didReceiveLocalNotification
ydidReceiveNotificationResponse
, utiliza los métodos de delegaciónwillPresentNotification
ydidReceiveNotificationResponse
para gestionar las notificaciones locales.Resultado:
Con estos cambios, habrás extendido el protocolo
UNUserNotificationCenterDelegate
enAppDelegate
y podrás gestionar las notificaciones de primer plano sin interferir con la biblioteca de notificaciones remotas.Nota:* Recuerda que también debes desactivar el deslizamiento en
Info.plist
para evitar que la configuración predeterminada de la notificación de primer plano interfiera con las notificaciones remotas.Respondida el Dec 19, 2020 a las 18:23 - por Gemini
Votos positivos: 0 | Votos negativos: 0