Skip to content

Instantly share code, notes, and snippets.

@aoverholtzer
Created April 16, 2023 21:26
Show Gist options
  • Save aoverholtzer/cd21342359cf19aca7375e611c07b352 to your computer and use it in GitHub Desktop.
Save aoverholtzer/cd21342359cf19aca7375e611c07b352 to your computer and use it in GitHub Desktop.
UIApplication and its methods are not available in iOS extensions, such as Share Extensions or Custom Keyboards. However, you can hack your way to, say, openURL if you really need to…
import UIKit
extension UIApplication {
public static func hacked_sharedApplication() -> UIApplication {
let selector = NSSelectorFromString("sharedApplication")
guard UIApplication.responds(to: selector) else {
fatalError("UIApplication.sharedApplication(): `UIApplication` does not respond to selector `sharedApplication`.")
}
guard let unmanagedSharedApplication = UIApplication.perform(selector) else {
fatalError("UIApplication.sharedApplication(): `UIApplication.sharedApplication()` returned `nil`.")
}
guard let sharedApplication = unmanagedSharedApplication.takeUnretainedValue() as? UIApplication else {
fatalError("UIApplication.sharedApplication(): `UIApplication.sharedApplication()` returned not `UIApplication` instance.")
}
return sharedApplication
}
@discardableResult
public func hacked_openURL(url: URL) -> Bool {
let selector = NSSelectorFromString("openURL:")
if InvocationHelper().perform(selector, with: url, target: self) {
return true
} else {
return false
}
}
public func hacked_canOpenURL(_ url: URL) -> Bool {
let selector = NSSelectorFromString("canOpenURL:")
if InvocationHelper().perform(selector, with: url, target: self) {
return true
} else {
return false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment