Search code examples
iosswiftmodel-view-controllerappdelegateuiapplication

UIApplicationMain class function inside ViewController


I have a functionality throughout my application. Now i need to call a specific function inside one view controller for some particular condition. So i tried to call, but it fails

main.swift

CommandLine.unsafeArgv.withMemoryRebound(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc))
{   argv in
    _ = UIApplicationMain(CommandLine.argc, argv, NSStringFromClass(MyClass.self), NSStringFromClass(AppDelegate.self))
}

MyClass.swift

class MyClass: UIApplication {
  func resetIdleTimer() {

  }
}

MyViewController.swift

class MyViewController: UIViewController {
    MyClass.resetIdleTimer(); //this causes error in 
}

I need to call resetIdleTimer() inside MyViewController?


Solution

  • Check this code, You can call it from anywhere.

    if let obj = MyClass.shared as? MyClass {
        obj.resetIdleTimer()
    }
    

    For ex. You can call in view controller

    class MyViewController: UIViewController {
        override func viewDidLoad() {
          super.viewDidLoad()
          if let obj = MyClass.shared as? MyClass {
              obj.resetIdleTimer()
          }
        }
    }