Как открыть контроллер представления уведомлений при получении push-уведомлений iOS? - PullRequest
1 голос
/ 25 апреля 2019

Я работаю в swift 4.2, а Push-уведомление получено от FireBase. Когда я нажимаю Notification, он переходит на домашнюю страницу. Но я хочу перейти на страницу Notification.

Это Swift4.2, Xcode 9.3, iOS 12.1. В прошлом я пытался, но не работал Foreground и InActive приложение

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()

        UINavigationBar.appearance().barTintColor = UIColor(red: 0/255.0, green: 85/255.0, blue: 127/255.0, alpha: 1)
        UINavigationBar.appearance().tintColor = UIColor.white
        //        UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white,NSAttributedString.Key.font: UIFont(name: "Roboto-Medium", size: 16)!]
        UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -60), for:UIBarMetrics.default)
        UINavigationBar.appearance().isTranslucent = false

        UIApplication.shared.statusBarStyle = .lightContent

        IQKeyboardManager .shared().isEnabled = true
        IQKeyboardManager .shared().shouldResignOnTouchOutside = true
        IQKeyboardManager .shared().isEnableAutoToolbar = false

        if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {

            // If your app wasn’t running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions

            let aps = notification["aps"] as! [String: AnyObject]
            UIApplication.shared.applicationIconBadgeNumber = 0


        }            

        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()


        let mainview = UIStoryboard(name:"Main", bundle: nil).instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
        let nav = UINavigationController.init(rootViewController: mainview)
        SideMenu = LGSideMenuController.init(rootViewController: nav)
        SideMenuView = UIStoryboard(name:"Main", bundle: nil).instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController
        SideMenu.rightViewStatusBarVisibleOptions = .onAll
        let rect = SideMenuView.view.frame;
        SideMenuView.view.frame = rect


        Messaging.messaging().delegate = self
        //        Siren.shared.wail()

        if launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil {
            // Do your task here
            let dic = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? NSDictionary
            let dic2 = dic?.value(forKey: "aps") as? NSDictionary
            let alert = dic2?.value(forKey: "alert") as? NSDictionary
            let category = dic2?.value(forKey: "title") as? String
            // We can add one more key name 'click_action' in payload while sending push notification and check category for indentifying the push notification type. 'category' is one of the seven built in key of payload for identifying type of notification and take actions accordingly
            if category == "News Added"
            {
                /// Set the flag true for is app open from Notification and on root view controller check the flag condition to take action accordingly
                AppConstants.sharedInstance.userDefaults.set(true, forKey: AppConstants.sharedInstance.kisFromNotificationSecond)
            }
            else if category == "1-2-1 notification"
            {
                AppConstants.sharedInstance.userDefaults.set(true, forKey: AppConstants.sharedInstance.kisFromNotificationThird)
            }
        }


        return true
    }

Ответы [ 2 ]

0 голосов
/ 25 апреля 2019

Здесь необходимо обработать два случая: один для случая, когда application жив, а другой для того, когда его нет.

Когда приложение живо, вы получите обратный вызов вdidReceiveNotificationResponse функция UserNotificationCenterDelegate.Вы можете обработать его соответствующим образом.

Когда приложение запускается, вам придется использовать клавишу UIApplication.LaunchOptionsKey.remoteNotification, которую вы получаете от функции didFinishLaunchingWithOptions в вашей AppDelegate

0 голосов
/ 25 апреля 2019

Для состояния убийства ИЛИ состояния завершения:

Определить новое свойство в AppDelegate.swift файл

var isFromNotification = false

Внести следующие изменения в AppDelegate.swift и оставьте остаток кода таким, какой он есть.

if launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil {
    isFromNotification = true
    //other required code
}

Перейдите на Homepage.swift файл

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated).

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    if appDelegate.isFromNotification {
        appDelegate.isFromNotification = false
        //Push to your notification controler without animation
    }
}

Обновление: для фона и состояния переднего плана

Вышеуказанный ответ относится только к состоянию убийства, как упомянуто в комментарии @ Абу Уль Хассан

Теперь давайте разберемсяпоток о состоянии фона или переднего плана.

userNotificationCenter (_: didReceive: withCompletionHandler:) метод вызывается, когда пользователь нажимает на уведомление в фоновом режиме или в режиме переднего плана.

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    //other required code
    //Get current navigation controller and redirect into notification screen
    completionHandler()
}

Как получить текущий UIViewController или текущий UINavigationController

Пожалуйста, отметьте как принятый, если работал.

Спасибо

...