Created
March 28, 2015 19:39
-
-
Save ruslanskorb/1616f0bdd1c2f6d45595 to your computer and use it in GitHub Desktop.
Avoids compile time errors about the using of `[UIApplication sharedApplication]` in an app extension.
Actually found the answer from another one of Ruslan's posts on the AFNetworking issue tracker:
UIApplication *application = [UIApplication rsk_sharedApplication];
if (application) {
// call any method of the app instance
}
Any chance you'll make this swizzled over using this current implementation?
How about much more simpler:
extension UIApplication {
func safeSharedApplication() -> UIApplication? {
guard UIApplication.respondsToSelector("sharedApplication") else {
return nil
}
guard let unmanagedSharedApplication = UIApplication.performSelector("sharedApplication") else {
return nil
}
return unmanagedSharedApplication.takeRetainedValue() as? UIApplication
}
}
@shergin The method sharedApplication
is available in the App Extension. It is only marked as unavailable for developers. Because of this UIApplication.performSelector("sharedApplication")
will return UIApplication
object. But its use is prohibited.
I think your method will work safely if you add a check of the suffix of the bundle path. As I mentioned earlier on stackoverflow when you build an extension based on an Xcode template, you get an extension bundle that ends in .appex.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you use your gist besides adding it to the Extension target?