Search code examples
iosswiftuiapplication

How to access UIApplication subclass functions


I have VC1 that is subclass of UIApplication

VC1

   class CustomUIApplication: UIApplication {
       override func sendEvent(_ event: UIEvent) {
            super.sendEvent(event)
       }
            
       func stopTimer() {
                   
       }
            
       func startTimer() {
                    
       }
   }

VC2

class MyVC: ViewController {
   // want to access start timer func here
}

Instance of CustomUIApplication will be in main.swift

UIApplicationMain(
    CommandLine.argc,
    CommandLine.unsafeArgv,
    NSStringFromClass(CustomUIApplication.self),
    NSStringFromClass(AppDelegate.self)
)

Any help would be appreciated and advance thanks.


Solution

  • According to docs:

    Every iOS app has exactly one instance of UIApplication (or, very rarely, a subclass of UIApplication). When an app is launched, the system calls the UIApplicationMain(::::) function; among its other tasks, this function creates a Singleton UIApplication object. Thereafter you access the object by calling the shared class method.

    So in MyVC you should be able to do CustomUIApplication.shared.startTimer().

    Said that, may I suggest you to consider having a separate class for handling start/stop time functionality, instead of having a subclass of UIApplication? You can make your own singleton for that and access it from wherever you need in a similar way.

    EDIT: Of course, you have to define static var shared: Self { UIApplication.shared as! Self } first. (Per @Sulthan's comment)