How to access keyWindow in share extension in ios?

3.2k views Asked by At

I need to access keyWindow in share extension for my app to
- Add some indicator view
- Access the width and height of window

I wrote the following line in the share extension classes:

UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow];

But, it's saying 'sharedApplication' is unavailable.
How can i access keyWindow in share extension?

Need your valuable suggestions.
Thanks in advance

3

There are 3 answers

0
Boudhayan On

Shared Application is not available to extensions. You can not access key window from share extension.You can subclass ShareExtension View controller from UINavigationController and can present a modal view controller then navigation also possible. In that modal view controller you can add activity indicator.

0
kev On

UIApplication is unavailable for extensions. To add an indicator view, you'll have to do that via your UIViewController stack, but you CAN get the size of the screen, which might suffice depending upon the exact use case (swift):

UIScreen.mainScreen().bounds.size

Read more here about the differences between [UIScreen mainScreen].bounds vs [UIApplcation sharedApplication].keyWindow.bounds?

Update

An alternative to using a UIScreen to get size is to navigate the view hierarchy. This works anywhere in a UIView or UIViewController where the view has been laid out. You can also add the indicator to the top most view.

// Find the top most view
var view: UIView = self;
while let higherView = view.superview {
    view = higherView;
}

// Size you need
var size: CGSize = view.frame.size;

// Add the indicator
let indicator: UIView = UIView(frame: CGRectMake(100, 100, 100, 100));
indicator.backgroundColor = UIColor.orangeColor();
view.addSubview(indicator);
view.bringSubviewToFront(indicator);
0
xy z On
UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
UIWindow *keyWindow = application.keyWindow;

however, keyWindow is nil...