0

I need a lot of help. I have a project that receives push notifications from the console of firebase without any problem, but now I have to implement the code that allows me to receive pushes from a console made in php. I do not know how to do it. I did research on research but nobody can explain this thing. Can someone help me? Below is AppDelegate.swift if it can serve Thank you all.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,MessagingDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
        application.registerForRemoteNotifications()
        Messaging.messaging().delegate = self
        FirebaseApp.configure()
        if let token = InstanceID.instanceID().token(){
            print("FIREBASE TOKEN: \(token)")
        }else{
            print("FIREBASE TOKEN NIL")
        }
        return true
    }

    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        if notificationSettings.types != .none {
            application.registerForRemoteNotifications()
        }
    }

    func setupPushNotification(application: UIApplication){
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge, .sound]) { (granted, error) in
            if granted {
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            } else {
                print("L'utente ha rifiutato: \(error?.localizedDescription ?? "error")")
            }
        }
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
        print("Message details: \(userInfo)")
        self.showAlertAppDelegate(title: "Okkey", message: "Test da applicazione aperta", buttonTitle: "OK", window: self.window!)
    }

    func connectToFCM(){
       Messaging.messaging().shouldEstablishDirectChannel = true
    }

    func applicationWillResignActive(_ application: UIApplication) {
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
       Messaging.messaging().shouldEstablishDirectChannel = false
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        connectToFCM()
    }

    func applicationWillTerminate(_ application: UIApplication) {
    }


    // MARK: UNUserNotificationCenterDelegate METHODS
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
        let tokenString = deviceToken.reduce("") { string, byte in
            string + String(format: "%02X", byte)
        }
        print("DEVICE TOKEN: ", tokenString)
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Notification Will Present")
        completionHandler([.alert, .badge, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print(response)
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        let newToken = InstanceID.instanceID().token()
        connectToFCM()
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print(fcmToken)
    }

    func showAlertAppDelegate(title: String, message: String, buttonTitle: String, window: UIWindow){
        let alert =  UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertAction.Style.default, handler: nil))
        window.rootViewController?.present(alert, animated: true, completion: nil)
    }

    func tokenString(_ deviceToken: Data) -> String {
        let bytes = [UInt8](deviceToken)
        var token = ""
        for byte in bytes {
            token += String(format: "%02x", byte)
        }
        return token
    }
}
Faysal Ahmed
  • 6,464
  • 5
  • 23
  • 43
  • Could you clarify your question? Are you after 1) ability to execute in your PHP-based application a request to a Firebase service to trigger remote notification to clients or 2) provide "direct communication" between PHP application and clients without utilising the Firebase service? – Peter Pajchl Nov 26 '18 at 12:35
  • @PeterPajchl Yeah sorry. It's true. I was not really clear in the question. I have a console that allows me to send push notifications for both android and iOS devices. The problem is that on Android devices arrive, but on those iOS do not arrive. What I want to know is if I have to implement other code, in addition to what I have already written for the console of firebase, which allows you to receive the push. –  Nov 26 '18 at 13:22

1 Answers1

0

Welcome to SO.

You have two options, I can't tell you the exact PHP code for the implementations but I can tell you the approaches and for sure you can find the code snippets on other SO posts.

First, I think it's the fastest, since you can send pushes from firebase, you can call from PHP the APIs from Firebase using the registrationToken received from Firebase SDK. Check this for more info.

Second, you can send the pushes from PHP directly, but for this you have to configure the certificates on the server side in order to connect to APNS servers. You have two modes for APNS, production & sandbox, for each mode you'll need a different certificate, usually a .pem file that can be generated like thisenter link description here (there are lots of post on how to generate .pem files). Just for you to know, if you run the app on device from Xcode, it uses the sandbox APNS mode for push notifications. If you create an ipa file it's using the production APNS so pay attention on these.

Also in order to send notifications from PHP, first you have to send the push token from app to your PHP server (it will be used for APNS). The token is received didRegisterForRemoteNotificationsWithDeviceToken (you already have that implemented).

danypata
  • 8,829
  • 1
  • 28
  • 41