Решение проблемы «didReceiveRemoteNotification» не выполняется при получении уведомления в ios swift 4 - PullRequest
0 голосов
/ 02 сентября 2018

в моем случае я использую FCM для push-уведомлений. Я сделал весь код в делегате приложения, но проблема в том, что когда я отправляю уведомление из fcm, оно работает успешно, но когда я запускаю со стороны PHP, это не работает и " didReceiveRemoteNotification "не выполняется. это код, который я сделал.

import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
import BRYXBanner

@available(iOS 10.0, *)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate,MessagingDelegate {

    var window: UIWindow?
    var strDeviceToken:String = ""
    var isView = ""
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


                UNUserNotificationCenter.current().delegate = self
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (isGranted, err) in
                guard isGranted else { return }
                self.getNotificationSettings()
                if err != nil {
                    //Something bad happend
                } else {
                    print(" if err != nil else......")
                    UNUserNotificationCenter.current().delegate = self
                    Messaging.messaging().delegate = self

                    DispatchQueue.main.async {
                          UNUserNotificationCenter.current().delegate = self
                        UIApplication.shared.registerForRemoteNotifications()

                    }
                }
            }
             UIApplication.shared.registerForRemoteNotifications()
             FirebaseApp.configure()
          if Global.isInternetAvailable(){

            }else{
                Global.showAlertMessageWithOkButtonAndTitle(GlobalConstant.APP_NAME, andMessage: "Check Your Internet")
            }



            IQKeyboardManager.shared.enable = true
            IQKeyboardManager.shared.shouldResignOnTouchOutside = true
            IQKeyboardManager.shared.enableAutoToolbar = true



            // create viewController code...
            let storyboard = UIStoryboard(name: "Main", bundle: nil)

            /// Introduction Navigation Controller
            let TeamViewController = storyboard.instantiateViewController(withIdentifier: "swr1") as! SWRevealViewController
            let BossViewController = storyboard.instantiateViewController(withIdentifier: "swr") as! SWRevealViewController
            /// Login Navigation Controller

            let selectUserTypeViewController  = storyboard.instantiateViewController(withIdentifier: "SlideShow") as! SlideShowViewController

            self.window?.makeKeyAndVisible()

            // Frist Launch of App check the NSUserDefault
            let isFirstLaunch = UserDefaults.standard.string(forKey: GlobalConstant.kkIsLogin) == nil
            if (isFirstLaunch)
            {
                UserDefaults.standard.set("00", forKey: GlobalConstant.kkIsLogin)
                UserDefaults.standard.synchronize()
            }

            // Check the isLogin
            let isUser = Global.getStringValue(UserDefaults.standard.value(forKey: "user_type") as AnyObject)
            print(isUser)

            if UserDefaults.standard.value(forKey: GlobalConstant.kkIsLogin) as! String == "1"
            {
                if isUser == "t"{
                    self.window?.rootViewController?.present(TeamViewController, animated: true, completion: nil)
                }else{
                    self.window?.rootViewController?.present(BossViewController, animated: true, completion: nil)
                }
            }
            else if UserDefaults.standard.value(forKey: GlobalConstant.kkIsLogin) as! String == "00"
            {
                UserDefaults.standard.set("0", forKey: GlobalConstant.kkIsLogin)
                UserDefaults.standard.synchronize()
                self.window?.rootViewController?.present(selectUserTypeViewController, animated: true, completion: nil)
            }
            else
            {
                UserDefaults.standard.synchronize()
                self.window?.rootViewController?.present(selectUserTypeViewController, animated: true, completion: nil)
            }

            // Override point for customization after application launch.
            return true
        }

       func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)
        {

            print("Firebase registration token::::::?????????????: \(fcmToken)")
           UserDefaults.standard.set(fcmToken, forKey: "deviceToken>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        }


        func getNotificationSettings() {
            UNUserNotificationCenter.current().getNotificationSettings { (settings) in
                print("Notification settings: \(settings)")
                guard settings.authorizationStatus == .authorized else { return }
                 DispatchQueue.main.async(execute: { UIApplication.shared.registerForRemoteNotifications() })
            }
        }

        func application(application: UIApplication,
                         didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
            Messaging.messaging().apnsToken = deviceToken as Data
        }

        func applicationWillResignActive(_ application: UIApplication) {

        }

        func applicationDidEnterBackground(_ application: UIApplication) {

            Messaging.messaging().shouldEstablishDirectChannel = true//false


        }

        func applicationWillEnterForeground(_ application: UIApplication) {
            // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

        }

        func applicationDidBecomeActive(_ application: UIApplication) {

            UIApplication.shared.applicationIconBadgeNumber = 0

        }

        func applicationWillTerminate(_ application: UIApplication) {

        }


        // Called when APNs failed to register the device for push notifications
        func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
            // Print the error to console (you should alert the user that registration failed)
            print("APNs registration failed: \(error)")
        }

        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
        {
            print("didReceiveRemoteNotificationv User Info = ",userInfo)


            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadChatTableView"), object: nil)


            GlobalConstant.notificationDict = userInfo

            let notificationDictionary: NSDictionary = GlobalConstant.notificationDict?["aps"] as! NSDictionary
            let type: String = Global.getStringValue(notificationDictionary.value(forKey: "type") as AnyObject)

            //        application.applicationIconBadgeNumber = application.applicationIconBadgeNumber + 1
            completionHandler(UIBackgroundFetchResult.noData)

            var aps: [AnyHashable: Any] = userInfo["aps"] as! [AnyHashable : Any]

            /// Check the isLogin
            if UserDefaults.standard.value(forKey: GlobalConstant.kkIsLogin) as! String == "1"
            {
                if UIApplication.shared.applicationState == .inactive || UIApplication.shared.applicationState == .background
           {            }

            }
            else
            {
                let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let loginNav: UINavigationController = UINavigationController(nibName: "LoginNavigationController", bundle: nil)
                let loginViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
                loginNav.viewControllers = [loginViewController]
                self.window?.rootViewController = loginNav
            }
        }

        // MARK:- UNUserNotificationCenter Delegate // >= iOS 10

        //Called when a notification is delivered to a foreground app.
        @available(iOS 10.0, *)
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            print(" willPresent User Info = ",notification.request.content.userInfo)
            completionHandler([.alert, .badge, .sound])

            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadChatTableView"), object: nil)

            UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1

            var aps: [AnyHashable: Any] = notification.request.content.userInfo["aps"] as! [AnyHashable : Any]

            /// Check the isLogin
            if UserDefaults.standard.value(forKey: GlobalConstant.kkIsLogin) as! String == "1"
            {

            } //====
            else
            {
                let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let loginNav: UINavigationController = UINavigationController(nibName: "LoginNavigationController", bundle: nil)
                let loginViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
                loginNav.viewControllers = [loginViewController]
                self.window?.rootViewController = loginNav
            }
        }

        //Called to let your app know which action was selected by the user for a given notification.
        @available(iOS 10.0, *)
        func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
            print("didReceive User Info = ",response.notification.request.content.userInfo)
            completionHandler()
            var aps: [AnyHashable: Any] = response.notification.request.content.userInfo["aps"] as! [AnyHashable : Any]
    //        UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1

            /// Check the isLogin
            if UserDefaults.standard.value(forKey: GlobalConstant.kkIsLogin) as! String == "1"
            {
                if UIApplication.shared.applicationState == .inactive || UIApplication.shared.applicationState == .background
                {

                }
                else
                {
                    let banner = Banner(title:GlobalConstant.APP_NAME , subtitle: aps["alert"] as? String, image: #imageLiteral(resourceName: "image-3"), backgroundColor: Global.hexStringToUIColor("#F3AF41"))
                    banner.springiness = .heavy
                    banner.position = .top
                    banner.didTapBlock =
                        {

                    }
                    banner.show(duration: 3.0)
                }
            }
            else
            {
                let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let loginNav: UINavigationController = UINavigationController(nibName: "LoginViewController", bundle: nil)
                let loginViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
                loginNav.viewControllers = [loginViewController]
                self.window?.rootViewController = loginNav
            }
        }

    }
...