5

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

Ashok
  • 5,585
  • 5
  • 52
  • 80
  • I read the answers but I have a similar problem. I cannot subclass the view controller because I have a custom UIWindow class that I want to add as subview to the 'keyWindow' in my share extension. Does anyone know how to do that? – Shwethascar Mar 22 '16 at 17:39
  • As of now 'keyWindow' is not available in share extension. Try to add your custom window to current viewcontroller's view, disable user interaction for viewcontroller's navigation bar if you have. I didn't try this but give it a try. – Ashok Mar 23 '16 at 14:04

3 Answers3

0

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.

Boudhayan
  • 750
  • 4
  • 15
0
UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
UIWindow *keyWindow = application.keyWindow;

however, keyWindow is nil...

xy z
  • 11
  • 2
-1

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);
Community
  • 1
  • 1
kev
  • 7,712
  • 11
  • 30
  • 41