Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
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:
Configuração do Certificado APNs:
Configuração do Projeto no Xcode:
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)")
}
}
Envio de Notificações do Servidor:
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)