Skip to content

Swift get UIApplication.sharedApplication().delegate

Some App would like to use system's UIApplication.sharedApplication().delegate as a global singleton object. Each App has a class of UIApplicationDelegate, and customer can add his own function into the class. For example, the delegate class is "MyDelegate", and add function "func f() {}".

In other place, whenever the customer wants to call the function f(), he can get global single object, convert to MyDelegate and call f.

let delegate = UIApplication.sharedApplication().delegate as! MyDelegate
delegate.f()

This works perfectly in Objective-C, however in Swift it may causing an exception:

Could not cast value of type 'SHInterceptor' (0x10ded4728) to 'MyDelegate'

This is because StreetHawk SDK takes over system delegate by "SHInterceptor", and it forwards all methods to "MyDelegate" while performing StreetHawk functions such as notification handling, open url etc. Objective-C works as expected however Swift is more restrictive in type checking so it throws the exception.

There are two solutions:

  • Get delegate by API "getAppDelegate" (recommended)
    StreetHawk SDK provides an API "getAppDelegate" for getting real "MyDelegate" object. It's very simple change:
let delegate = SHApp.sharedInstance().getAppDelegate() as! MyDelegate

Replace this line and all works perfectly.

  • Not take over system delegate by "SHInterceptor"
    This is suitable for advanced customers who want to control by themselves. By setting a flag before initialize StreetHawk library, it can avoid taking over system delegate.
SHApp.sharedInstance().autoIntegrateAppDelegate = false
SHApp.sharedInstance().registerInstallForApp("app_key", withDebugMode: true)

Then MyDelegate must forward necessary system callbacks to StreetHawk SDK. Here are the details.