Search code examples
iosswiftsdk

How to access application delegate from SDK on iOS?


I'm trying to access an application delegate from SDK that does not know the class name of the application delegate. I mean that my SDK doesn't know what class will be an application delegate in a basic project. So I find a class that conforms to the protocol UIApplicationDelegate.

    let numberOfClasses: UnsafeMutablePointer<UInt32> = UnsafeMutablePointer<UInt32>.alloc(0)
    let classes = objc_copyClassList(numberOfClasses)
    var appDelegateClass: AnyClass? = nil

    for i in 0...Int(numberOfClasses.memory) {
        if class_conformsToProtocol(classes[i], UIApplicationDelegate.self) {
            appDelegateClass = classes[i]
        }
    }

But the result has "type" "AnyClass?". The following code results getting an error "'applicationDelegateClass' is not a type":

    if let applicationDelegateClass = appDelegateClass {
        if let delegate = UIApplication.sharedApplication().delegate as? applicationDelegateClass.self { }
    }

How could I solve it?


Solution

  • I actually shouldn't use the specific application delegate class. The right code:

    if let delegate = UIApplication.sharedApplication().delegate! as? UIApplicationDelegate {}