Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

Como Configurar e Utilizar Push Notifications no Ambiente Apple

Push Notifications são uma ferramenta essencial para manter os usuários engajados e informados sobre atualizações importantes em tempo real. No ambiente Apple, as Push Notifications são gerenciadas através do Apple Push Notification Service (APNs). Este serviço permite que desenvolvedores enviem notificações para dispositivos iOS, iPadOS, macOS, watchOS e tvOS. Neste artigo, vamos explorar como configurar e utilizar Push Notifications em aplicativos Apple, com exemplos práticos e detalhados.

Exemplos:

  1. Configuração do Certificado APNs:

    • Acesse o Apple Developer Portal.
    • Vá para "Certificates, Identifiers & Profiles".
    • Crie um novo certificado APNs para o seu aplicativo.
    • Baixe o certificado e instale-o no seu servidor.
  2. Configuração do Projeto no Xcode:

    • Abra seu projeto no Xcode.
    • Navegue até as configurações do projeto e selecione o "Signing & Capabilities".
    • Adicione a capacidade "Push Notifications".
    • Adicione a capacidade "Background Modes" e marque a opção "Remote notifications".
  3. Código para Registrar o Dispositivo:

    import UIKit
    import UserNotifications
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
       var window: UIWindow?
    
       func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
           // Solicitar permissão para notificações
           UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
               if granted {
                   DispatchQueue.main.async {
                       UIApplication.shared.registerForRemoteNotifications()
                   }
               }
           }
           return true
       }
    
       func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
           // Converta o token do dispositivo para uma string
           let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
           let token = tokenParts.joined()
           print("Device Token: \(token)")
           // Envie o token para o servidor
       }
    
       func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
           print("Failed to register: \(error)")
       }
    }
  4. Envio de Notificações do Servidor:

    • Utilize uma biblioteca como apns2 para enviar notificações do servidor.
    • Exemplo em Python:

      from apns2.client import APNsClient
      from apns2.payload import Payload
      
      client = APNsClient('path/to/certificate.pem', use_sandbox=True, use_alternative_port=False)
      token_hex = 'device_token_here'
      payload = Payload(alert="Hello World!", sound="default", badge=1)
      topic = 'com.example.myapp'
      
      client.send_notification(token_hex, payload, topic)

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.