import UIKit
import GooglePlaces
import Firebase
import FirebaseMessaging
import UserNotifications
@main
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UserDefaults.standard.setValue(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
//google places key
GMSPlacesClient.provideAPIKey("googleAPIKey")
// Configure Firebase
FirebaseApp.configure()
Messaging.messaging().delegate = self
// Request authorization to receive push notifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
guard granted else { return }
// Register with FCM
UNUserNotificationCenter.current().delegate = self
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
return true
}
// Handle failing to register for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register for remote notifications: \(error.localizedDescription)")
}
// Handle receiving an FCM registration token
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("FCM registration token: \(fcmToken ?? "000")")
// Do something with the token
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Set APNS device token in FCM instance
Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
// Retrieve FCM token
Messaging.messaging().token { token, error in
if let error = error {
print("Error retrieving FCM token: \(error.localizedDescription)")
} else if let token = token {
print("FCM token: \(token)")
}
}
}
}
on my view Controller how i sent the notification :
func envoyerNotifClient(token:String){
// Créer une demande de notification
let notification = [
"to": token,
"notification": [
"title": "Batigreen",
"body": "vous avez recu un message !"
]
] as [String : Any]
// Convertir la demande de notification en JSON
let jsonData = try? JSONSerialization.data(withJSONObject: notification)
// Configurer la requête HTTP
let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("key=myKey", forHTTPHeaderField: "Authorization")
// Envoyer la notification
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Erreur lors de l'envoi de la notification: \(error.localizedDescription)")
return
}
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
print("Erreur lors de l'envoi de la notification, code de réponse HTTP: \(httpResponse.statusCode)")
return
}
print("Notification envoyée avec succès")
}
task.resume()
}