Swift - Push-уведомления из PHP - PullRequest
0 голосов
/ 26 ноября 2018

Мне нужна большая помощь.У меня есть проект, который получает push-уведомления с консоли firebase без каких-либо проблем, но теперь я должен реализовать код, который позволяет мне получать push-сообщения с консоли, созданной в php.Я не знаю как это сделать.Я занимался исследованиями, но никто не может объяснить это.Кто-нибудь может мне помочь?Ниже приведен AppDelegate.swift, если он может служить Спасибо всем.

@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
    }
}

1 Ответ

0 голосов
/ 26 ноября 2018

Добро пожаловать в SO.

У вас есть два варианта, я не могу сказать вам точный код PHP для реализаций, но я могу рассказать вам о подходах и наверняка вы можете найти фрагменты кода в других SOposts.

Во-первых, я думаю, что это самый быстрый, так как вы можете отправлять push-сообщения из firebase, вы можете вызывать из PHP API-интерфейсы из Firebase, используя регистрационный ключ, полученный из Firebase SDK.Проверьте this для получения дополнительной информации.

Во-вторых, вы можете отправлять запросы из PHP напрямую, но для этого вам необходимо настроить сертификаты на стороне сервера для подключения к серверам APNS.У вас есть два режима для APNS, production и sandbox, для каждого режима вам понадобится отдельный сертификат, обычно файл .pem, который можно сгенерировать следующим образом: введите описание ссылки здесь (там много сообщений накак генерировать .pem файлы).Просто для вас, чтобы знать, если вы запускаете приложение на устройстве из XCode, оно использует режим APNS песочницы для push-уведомлений.Если вы создаете файл ipa, он использует производственные APNS, поэтому обратите на них внимание.

Кроме того, чтобы отправлять уведомления из PHP, сначала необходимо отправить push-токен из приложения на ваш сервер PHP (это будетиспользуется для APNS).Токен получен didRegisterForRemoteNotificationsWithDeviceToken (он уже реализован).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...