Обнаружение неактивности (без взаимодействия с пользователем) в iOS для отображения отдельного экрана, как наложение - PullRequest
0 голосов
/ 20 ноября 2018

Как обнаружить неактивность или отсутствие взаимодействия с пользователем в iOS App.Для отображения отдельного экрана, такого как наложение или что-то вроде заставки.По следующей ссылке ссылка, которая использовалась для отображения наложения экрана, когда приложение стало неактивным , я могу показать заставку в приложении.Но при обычном коде диспетчера представления dismiss не удается отклонить представленный контроллер представления.

 we are presenting the custom overlay using

// The callback for when the timeout was fired.
    func applicationDidTimout(notification: NSNotification) {

       let storyboard = UIStoryboard(name: "MyStoryboard", bundle: nil)
              let vc = 
 storyboard.instantiateViewControllerWithIdentifier("myStoryboardIdentifier")
        UIApplication.shared.keyWindow?.rootViewController = vc       
    }

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

1 Ответ

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

Из комментария @Prabhat Kesara и @Vanessa Forney в ответной ссылке.Я пришел с приведенным ниже решением, и оно работает нормально.Если кто-то приходит с таким требованием, он может использовать это

import UIKit
import Foundation

extension NSNotification.Name {
    public static let TimeOutUserInteraction: NSNotification.Name = NSNotification.Name(rawValue: "TimeOutUserInteraction")
}

class UserInterractionSetup: UIApplication {

    static let ApplicationDidTimoutNotification = "AppTimout"

    // The timeout in seconds for when to fire the idle timer.

    let timeoutInSeconds: TimeInterval = 1 * 60 //5 * 60 //

    var idleTimer: Timer?

    // Listen for any touch. If the screen receives a touch, the timer is reset.

    override func sendEvent(_ event: UIEvent) {

        super.sendEvent(event)


        if idleTimer != nil {

            self.resetIdleTimer()

        }

        if let touches = event.allTouches {

            for touch in touches {

                if touch.phase == UITouch.Phase.began {

                    self.resetIdleTimer()

                }

            }

        }

    }


    // Resent the timer because there was user interaction.

    func resetIdleTimer() {

        if let idleTimer = idleTimer {

            // print("1")

            let root = UIApplication.shared.keyWindow?.rootViewController

            root?.dismiss(animated: true, completion: nil)

            idleTimer.invalidate()

        }


        idleTimer = Timer.scheduledTimer(timeInterval: timeoutInSeconds, target: self, selector: #selector(self.idleTimerExceeded), userInfo: nil, repeats: false)

    }

    // If the timer reaches the limit as defined in timeoutInSeconds, post this notification.

    @objc func idleTimerExceeded() {

        print("Time Out")
         NotificationCenter.default.post(name:Notification.Name.TimeOutUserInteraction, object: nil)

        let screenSaverVC = UIStoryboard(name:"ScreenSaver", bundle:nil).instantiateViewController(withIdentifier:"LandingPageViewController") as! LandingPageViewController

        if let presentVc = TopMostViewController.sharedInstance.topMostViewController(controller: screenSaverVC){


            let root: UINavigationController = UIApplication.shared.keyWindow!.rootViewController as! UINavigationController

            if let topView = root.viewControllers.last?.presentedViewController {

                topView.dismiss(animated: false) {

                    root.viewControllers.last?.navigationController?.present(presentVc, animated: true, completion: nil)

                }

            }else if let topViewNavigation = root.viewControllers.last {

                topViewNavigation.navigationController?.present(presentVc, animated: true, completion: nil)



            }

        }

    }

}

. Трудность, с которой я столкнулся, заключалась в наложении или хранении экрана над уже представленным представлением.В этом случае мы также рассматриваем вышеуказанное решение.Удачного кодирования :)

...