Notificações push no iOS

Prev Next

Configure notificações push dentro do Xtremepush e do seu app

Notificações push para iOS exigem certificados gerados a partir da sua conta Apple Developer. Siga estes passos para ativar notificações push:

Obtenha certificados Apple

  1. Faça login na sua conta Apple Developer em (https://developer.apple.com/membercenter/)

  2. Selecione Certificados, IDs e Perfis

  3. Identificadores Selecionados

    196

  4. Selecione o aplicativo que você está integrando com o Xtremepush e clique em Editar.

  5. Nas Configurações do ID do App iOS, clique em Editar ao lado de Notificações Push.

    805

  6. Em Certificado SSL de Desenvolvimento, clique em "Criar Certificado" e siga as instruções passo a passo para gerar e baixar o certificado.

    679

  7. Repita esse procedimento para gerar e baixar um certificado sob "Production SSL Certificate".

  8. Abra os certificados, que os mostrarão no aplicativo Keychain Access.

  9. Selecione a certificação e expanda-a para ver a chave abaixo.

  10. Segure ⌘Cmd para selecionar tanto o certificado quanto a chave e exportá-los usando Arquivo > Exportar Itens..., escolhendo o formato (.p12).

Configure Xtremepush

  1. No Xtremepush, navegue até **Configurações > Apps & sites > clique no app iOS correspondente > Push > Push Settings.

  2. Faça upload dos certificados de Produção e Sandbox (desenvolvimento) e pressione Salvar.

Adicionar ao aplicativo

Para testes básicos, você pode adicionar a função de notificação register push do SDK ao seu didFinishLaunchingWithOptions método no seu Application Delegate. Para uma melhor experiência do usuário, o registro de notificações push só deve ser acionado após um prompt ou troca de valor no seu app, assim seus usuários entendem por que as permissões push estão sendo solicitadas e têm mais chances de concordar em aderir. Saiba mais em nosso guia dedicado aqui.

O Xtremepush não exige que você defina o Delegado do UNUserNotificationCenter, pois isso entrará em conflito com nossa biblioteca.

Se você testar usando builds de desenvolvimento, então deve ativar o Modo Sandbox , já que a Apple usa um gateway diferente para compilações compiladas com um perfil de provisão móvel de desenvolvimento. Se você só fizer builds empresariais, não vai precisar disso. Defina o modo sandbox em uma instrução que só rodará para builds de desenvolvimento, pois não deve ser ativado em produção.

Dentro didFinishLaunchingWithOptions de mim, adicione o seguinte:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    XPush.setAppKey("XPUSH_APP_KEY")
    // Add registration for push notifications
    XPush.register(forRemoteNotificationTypes: [.alert, .badge, .sound]);
    // Set push notification sandbox mode only for development builds
    #if DEBUG
    XPush.setSandboxModeEnabled(true)
    #endif
    XPush.applicationDidFinishLaunching(options: launchOptions)
    return true
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [XPush setAppKey: @"XPUSH_APP_KEY"];
    // Add registration for push notifications
    [XPush registerForRemoteNotificationTypes:XPNotificationType_Alert | 
    XPNotificationType_Sound | XPNotificationType_Badge];
    // Set push notification sandbox mode only for development builds
    #if DEBUG     
    [XPush setSandboxModeEnabled:YES];     
    #endif 
    [XPush applicationDidFinishLaunchingWithOptions:launchOptions];
}

Adicione os seguintes métodos de gerenciamento de notificações remotas do iOS no delegado de aplicação e coloque a chamada correspondente ao método Xtremepush em cada um deles, conforme mostrado.

func application(_ application: UIApplication, 
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
    XPush.applicationDidRegisterForRemoteNotifications(withDeviceToken: deviceToken as Data!)
}
func application(_ application: UIApplication,
    didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    XPush.applicationDidFailToRegisterForRemoteNotificationsWithError(error)
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [XPush applicationDidRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    [XPush applicationDidFailToRegisterForRemoteNotificationsWithError:error];
}

Usando o UNUserNotificationCenterDelegate com o SDK XPush para iOS

Por que isso importa:

O SDK XPush depende de retornos UNUserNotificationCenterDelegate para:

  • Trilha Push/Clique

  • Comportamento de apresentação em primeiro plano de lidar

  • processar ações de notificação específicas do XPush

Importante:

O iOS permite apenas um delegado do UNUserNotificationCenter. Se seu app definir seu próprio delegado, o XPush não receberá mais essas chamadas de retorno a menos que você as encaminhe.

Abordagem recomendada:

Se você precisar de um delegado personalizado (por exemplo, para lidar com outro provedor de push), ainda pode fazer isso — basta encaminhar as notificações XPush para o SDK.

  1. Defina o delegado Defina seu delegado uma vez durante a inicialização do app:

UNUserNotificationCenter.current().delegate
[UNUserNotificationCenter currentNotificationCenter].delegate = self;

  1. Encaminhe notificações para XPush nos métodos delegados

import UserNotifications
import XPush

final class YourNotificationHandlerClass: NSObject, UNUserNotificationCenterDelegate {

    // Called when a notification is received while the app is in the foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        if userInfo["xpush"] != nil {
            // Forward XPush notifications to the SDK
            XPush.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)
            return // SDK calls completionHandler
        }
        // Handle non-XPush notification actions here, if applicable
        completionHandler([.banner, .list, .sound])
    }

    // Called when the user taps a notification or interacts with an action button
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        let userInfo = response.notification.request.content.userInfo
        if userInfo["xpush"] != nil {
            // Forward XPush notifications to the SDK
            XPush.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler)
            return // SDK calls completionHandler
        }
        // Handle non-XPush notification actions here, if applicable
        completionHandler()
    }
}
#import <UserNotifications/UserNotifications.h>
#import <XPush/XPush.h>
@interface YourNotificationHandlerClass () <UNUserNotificationCenterDelegate>
@end
@implementation YourNotificationHandlerClass
#pragma mark - UNUserNotificationCenterDelegate
// Called when a notification is received while the app is in the foreground
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSDictionary *userInfo = notification.request.content.userInfo;
    if (userInfo[@"xpush"] != nil) {
        // Forward XPush notifications to the SDK
        [XPush userNotificationCenter:center
              willPresentNotification:notification
                withCompletionHandler:completionHandler];
        return; // SDK calls completionHandler
    }
    // Handle non-XPush notifications here (if applicable)
    completionHandler(UNNotificationPresentationOptionAlert);
}
// Called when the user taps a notification or interacts with an action button
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    if (userInfo[@"xpush"] != nil) {
        // Forward XPush notifications to the SDK
        [XPush userNotificationCenter:center
     didReceiveNotificationResponse:response
              withCompletionHandler:completionHandler];
        return; // SDK calls completionHandler
    }
    // Handle non-XPush notification actions here (if applicable)
    completionHandler();
}
@end

Notas:

  • Verificamos userInfo[@"xpush"] para direcionar apenas notificações XPush para o SDK.

  • Volte imediatamente após chamar o XPush para não chamar o completionHandler duas vezes sem querer.

  • Se você apoia outros prestadores, lide com aqueles no caminho do outro.