Cocoa: NSUserNotification appears behind NSPopover - objective-c

I have no idea where to even start trying to fix this but maybe someone can point me in the right direction. I have a status item application that shows a popover when clicked, some user interactions produce an NSUserNotification to warn/inform about changes or errors. But when the notification appears it is shown behind the popover, so if they overlay the user can't read what it says.
Is there a way to force the notification to appear in front of the popover? Like order the notification to the front.
Edit: here's a picture showing part of the notification hidden behind the popover after a user gave bad input. I don't really want to hide the popover to show the error notification.
I've tried stuff lake makeKeyAndOrderFront, activateIgnoringOtherApps, the type of stuff you'd use on a window, but none of it applies to an NSUserNotification so it doesn't work.
Edit 2: I should note that to get the popover to appear in front of everything when called I use activateIgnoringOtherApps and becomeFirstResponder on the popover, but even getting rid of that still shows the notification behind the popover.
Edit 3: The popover is shown relative to a status item in the status bar using
[[self popover] showRelativeToRect:statusItem.view.bounds ofView:statusItem.view preferredEdge:NSMaxYEdge];
When clicked, the status item calls a method that does this:
- (void)openPopover:(id)sender {
if (![_popover isShown] | (_popoverIsClosing)) {
[_preferencesWindow close];
[NSApp activateIgnoringOtherApps:YES];
[_popover becomeFirstResponder];
[statusItemView setHighlighted:YES];
[[self popover] showRelativeToRect:statusItem.view.bounds ofView:statusItem.view preferredEdge:NSMaxYEdge];
[self performSelector:#selector(defaultTextField)];
NSLog(#"popover opened");
} else {
[_preferencesWindow close];
[NSApp activateIgnoringOtherApps:NO];
NSLog(#"popover closed");
[_popover close];
[_popover resignFirstResponder];
[[NSApplication sharedApplication] hide: self];
[statusItemView setHighlighted:NO];
}
}
Thanks for the help.

You want to adjust the window.level.
A notification is using level 18, so as long as your level is lower, you will not have this issue.
You can use these default NSWindow.Level
.normal = 0
.floating = 3
.submenu = 3
.tornOffMenu = 3
Or a custom level NSWindow.Level(rawValue: 17).
An important thing to note is you should set the windows level during or after the popover did show. Otherwise your setting will be reset.
You can do this from the popover.delegate using the function,
func popoverDidShow(_ notification: Notification)
Or listen to the notification directly with NSPopoverDidShowNotification.
This has been tested on macOS 10.15

Related

Display loading notification or gif during an operation in a Cocoa app (not cocoa touch)

I have an app in which I am uploading data from a device, while the device is being read I would like to display a little loading notification or overlay. Does Cocoa have something like this built in? If I'm not mistaken I believe cocoa touch used to. Basically on a button event that starts the device reading I would also like to fire off the overlay.
The code I would add to is below:
- (IBAction)uploadEvent:(id)sender
{
// start loading overlay
char *encodedBuffer = NULL;
HEM6310FDriver *driver = [[HEM6310FDriver alloc] init];
int getDataFromDevice = [driver getData:encodedBuffer user: 1];
if (getDataFromDevice == Success) {
int status = upload(driver.deviceData);
//remove loading overlay
}
else{
// do something else and remove overlay
}
The appropriate thing to do is to add an NSProgressIndicator to your view hierarchy and display and animate when the request begins.
If it is a determinate progress, use callbacks to update.
You should also setEnabled: NO on views and controls that need the data until progress is complete.
You might also look at the new NSProgress API
Create a NSPanel. It can be as simple as you want. Maybe just a label that says "Loading" and a NSProgressView in indeterminate mode. You can then attach it to the window like this:
[[NSApplication sharedApplication] beginSheet:loadingPanel
modalForWindow:self.window
modalDelegate:self
didEndSelector:nil
contextInfo:nil];
When you want to dismiss it, do this:
[[NSApplication sharedApplication] endSheet:loadingPanel returnCode:0];
[loadingPanel orderOut:nil];

NSPanel not receiving mousedragged event

I have a borderless NSPanel, when I first launch it and it has focus I can drag it around and the mousedragged method gets triggered correctly, however when I switch focus to another app and then return to the NSPanel (which is set with an NSNonactivatingPanelMask) I no longer receive the mousedragged events.
I do still receive mouseup and mousedown events, so I'm at a loss of why the mousedragged event isn't executed.
Any ideas?
Here's how it gets initialized:
_panel = [[MyPanel alloc] initWithContentRect:frame
styleMask:NSBorderlessWindowMask | NSNonactivatingPanelMask
backing:NSBackingStoreBuffered
defer:NO];
I've also tried adding all these methods to my panel class:
- (BOOL)canBecomeKeyWindow {
return YES;
}
- (BOOL)canBecomeMainWindow
{
return YES;
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (BOOL)acceptsFirstMouse
{
return YES;
}
And making it first responder in the mouse down (which it still receives):
- (void)mouseDown:(NSEvent *)theEvent
{
[self makeFirstResponder:self];
[self makeKeyWindow];
[self setBackgroundColor:[NSColor redColor]];
[self display];
}
The mousedragged simply contains this:
- (void)mouseDragged:(NSEvent *)theEvent
{
[self setBackgroundColor:[NSColor greenColor]];
[self display];
NSLog(#"dragged");
}
I do not want the window to get focus. (The focus should remain on the third party app below).
Update: I've added a sample project, download here: http://users.telenet.be/prullen/MovingPanel.zip
As you will see, when you first run the app, and drag it will output "dragged" in the console.log continuously (and the background color will be green). If you then switch to another app and then back to the movingpanel app, dragging will not output anything any more. (and the background color will be red, which is set in the mousedown event handler).
Without the NSNonactivatingPanelMask this works as it should, but it is vital that the window below my panel remains active. If there is another way to accomplish this, please do share.
One thing I have also noticed, if you double click on the panel (fast), and then drag, it turns green (so the mousedragged: is being called), but it's not moving... Not sure what to think of that.
I also noticed that if I do [self setMovableByWindowBackground:NO]; then it will also work correctly. I am betting that the way setMovableByWindowBackground works is interfering with the mouseDragged being called. It's probably a bug that it is called at all.
I would guess one possible solution would be to implement your own window dragging.
If what you are really interested in is responding to when the window is moving, this question and answer may provide what you need.
How to receive notifications when moving Window by mouse?

Application tried to present modally an active controller : UIImagePickerController

I'm struggle at this for 2 days and believe that this is the moment I should call for help. After I search SOF for a while, none of any answer could solve my problem. Here are my application ...
In the application,
Device is iPad, iOS 6
RootViewController is NavigationController
TopViewController is TabBarController
In this TabBarController, I present a popoverController from right bar button of navigation bar
In presenting popover there is a button to allow user to pick image from by taking new one or pick from existing.
To pick new one, I presentViewController UIImagePickerController to allow user to take photo with divice camera. presentModalViewController:animated: if iOS < 6, and presentViewController:animated:completion: for iOS > 6
I also hide Status Bar before presentation
To select from existing photo, I do presentPopoverFromBarButtonItem:permitArrowDirections:animated:
PopoverViewController also referencing by A TabBarController
Here is the issue
Present UIImagePickerController will always failed if user try to pick new one first with exception "Application tried to present modally an active controller <[name of view controller that try to present]>"
BUT, if user try to pick image from camera roll for once and then try to take new one again, it won't fail.
Here are what I tried
present from RootViewController
present from TopViewController (TabBarController)
present from popoverViewController itself
present from a tab of TabBarController
hide popoverViewController before presentation
resignFirstResponder from a textField in popoverViewController
Here is the current code I'm using
// PopoverViewController, presented by a tab in TabBarController
- (IBAction)takePhoto:(id)sender {
[self.delegate takePhotoWithDeviceCamera];
}
// A Tab in TabBarController, delegate of popoverViewController
- (void)takePhotoWithCamera {
[[UIApplication sharedApplication] setStatusBarHidden:YES];
if ([UIDevice OSVersion] < 6.0) {
[self presentModalViewController:cameraPicker animated:YES];
} else {
[self presentViewController:cameraPicker animated:YES completion:nil];
}
}
Any idea what would cause this error? Any suggestion are welcome. Thank you.
Got the same trouble than you and finally got the solution based on #CainaSouza's answer. I've been working with Xamarin.iOS so I'll make my answer in C#, but it can be easily translated to Objective-C.
I'm using the same code as #CainaSouza to call the controller:
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController (customController, true, null);
And then I add the following code to my custom RootViewController:
public override void PresentViewController (UIViewController viewControllerToPresent, bool animated, Action completionHandler)
{
if (PresentedViewController != viewControllerToPresent) {
base.PresentViewController (viewControllerToPresent, animated, completionHandler);
}
}
The trick is to check if you haven't presented that UIViewController before.
I know it's an old question, but hope it will help someone. :)
Present the imagePicker controller in a popoverController(in case of iPad). This will not give you that error.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:picker];
[popover presentPopoverFromRect:self.selectedImageView.bounds inView:self.selectedImageView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popOver = popover;
}
else {
[self presentModalViewController:picker animated:YES];
}
Best Regards.
Have you tried to present it like this?
[self.view.window.rootViewController presentModalViewController:cameraPicker animated:YES];
My guess is that the cameraPicker instance is not correctly allocated/released. Try creating the cameraPicker inside your - (void)takePhotoWithCamera method rather than relying on a previously created instance. You'll get a handle to the picker instance in the callback methods...
I had the same problem - I wanted users to take photos using a full screen view (i.e. call presentViewController and pass UIImagePickerController controller instance) and select existing photos from a popover (I associated it with a popover using initWithContentViewController). I reused the same instance of UIImagePickerController for both camera and popover and it threw the same exception if I tried to run a camera before opening a popover.
I turned out to cause a problem and my solution was simply to have two instances of UIImagePickerController - one for camera (which I presented from a main view) and another one for popover. It works so far. :-)
Not sure if it is still actual for the original poster, but hopefully it will help anyone else who encounter this discussion.

Show Window without activating (keep application below it active)

I need to show a window (without title bar) above third party applications without my window taking focus.
I have tried using an NSPanel and setting enabling non-activating, but that didn't help.
I tried orderFront:self, but that didn't help either.
I always needed to add [NSApp activateIgnoringOtherApps:YES]; because the window wouldn't show otherwise.
I have here a sample project for just this functionality:
http://users.telenet.be/prullen/TopW2.zip
UIElement is set to true in the application's plist file, so there is no dock. You can activate the window by pressing ALT + SPACE at the same time. You will see that the app below it looses focus. Any thoughts on how to fix this? I've seen other apps do it so I know it's possible.
Edit: here's the code so far. Remember the window is a non-activating NSPanel.
I still need that last NSApp activateIgnoringOtherApps line or otherwise it doesn't display. But of course that makes the window the active one.
_windowController = [[MyWindowController alloc] initWithWindowNibName:#"MyWindowController"];
[[_windowController window] setLevel:NSNormalWindowLevel+1];
[[_windowController window] orderFrontRegardless];
[_windowController showWindow:self];
[NSApp activateIgnoringOtherApps:YES];
I've also subclassed NSPanel and added two methods:
- (BOOL)canBecomeKeyWindow
{
return YES;
}
- (BOOL)canBecomeMainWindow
{
return YES;
}
Edit: OK, unchecking setHidesOnDeactivate fixes this, but now the window will never hide. I need it to hide when the user presses the app below it or switches to another app.
Edit 2: OK, this seems to fix the above issue:
- (void)awakeFromNib
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(hideWindow) name:NSWindowDidResignKeyNotification object:nil];
}
- (void)hideWindow {
[self setHidesOnDeactivate:YES];
}
Not sure if there's a better way.
And for those that want to know how to display the window:
[[_windowController window] setLevel:NSPopUpMenuWindowLevel];
[[_windowController window] orderFrontRegardless];
[[_windowController window] makeKeyWindow];
[_windowController showWindow:self];
Either one of these should do the trick:
Use -[NSWindow orderFrontRegardless] to get a normal level window to the front without activating the corresponding app, or
Use -[NSWindow setLevel:] to increase the window level to something higher than NSNormalWindowLevel
Not to take away from #puzzle's useful answer, but it sounds like your problem has something to do with using an NSPanel instead of an NSWindow.
The "How Panels Work" docs say:
Onscreen panels, except for alert dialogs, are removed from the screen when the application isn’t active and are restored when the application again becomes active. This reduces screen clutter.
Specifically, the NSWindow implementation of the hidesOnDeactivate method returns NO, but the NSPanel implementation of the same method returns YES.
So perhaps you could override hidesOnDeactivate to return NO, or change to NSWindow

subview from UIWindow and sending it back to UIwindow

I have an UIWebView loaded with div, act as editor to write. Now i am adding UIWebView as sub view on UIWindow to set the frame equal to full screen and to hide the UIKeyboard, but at some button method, i need to get UIWebview from UIWindow and sent it back to UIKeyboard. Here is my code which is not working:
keyboardWindowFrame= nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows])
{
if (![[testWindow class] isEqual:[UIWindow class]])
{
keyboardWindowFrame = testWindow;
[webViewForEditing setFrame:CGRectMake(5, 63, 310, 400)];
[webViewForEditing.scrollView setContentSize:CGSizeMake(310, 400)];
[keyboardWindowFrame addSubview:webViewForEditing];
break;
}
}
- (IBAction)keyboardButtonSelected:(id)sender
{
[keyboardWindowFrame sendSubviewToBack:webViewForEditing]; //need to send UIWebView back to UIWindow so i can write
}
I think I am trying to do the same thing as you and so although your question is not particularly clear hopefully my answer will help.
It seems that you have a view 'webViewForEditing' which you want to add and bring in front of the keyboard. When you click a button you want to put this view behind the keyboard again.
I have also tried using the sendSubViewToBack code with no joy.
In the end though I managed to get it to work using:
[[self view] exchangeSubviewAtIndex: withSubviewAtIndex: ];
(Credit goes to Sunny with it adapted from a question here)
I used the following code below, with to switch between a UIView and the keyboard:
- (IBAction)toggleButtonPressed:(id)sender {
UIWindow * window = [UIApplication sharedApplication].windows.lastObject;
if (window.subviews.count == 1) {
[window addSubview:_menuView];
}
else {
[window exchangeSubviewAtIndex: 0 withSubviewAtIndex: 1];
}
}
I am only working with two views (_menuView and the keyboard) which means I check how many subviews my window has to make sure I only add _menuView once.
Then it is easy to exchange the two views.
Even if you had more subviews in your window I am sure you could use a modified version of this. As long as none of your other views change places then exchanging them will always switch the same two views.
NOTE: As an aside. I am not sure if this code works if called when the keyboard is not first responder. I get the variable for Window using the last object in the window, which is always the keyboard if it has been made first responder. It might need tweaking to get it working at other times.
I formulated another, more eloquent, answer while working on this:
Add the views you want to the window view that holds the keyboard view:
#interface BViewController : UIViewController {
UIWindow * window;
}
// Add the code when the keyboard is showing to ensure it is added while we have a keyboard and to make sure it is only added once
-(void) keyboardDidShow: (NSNotification *) notification {
window = [UIApplication sharedApplication].windows.lastObject;
if (window.subviews.count == 1) {
[window addSubview:_menuView];
[window addSubview:_gameView];
[window addSubview:_stickerView];
[self hideViews];
}
}
- (void)hideViews {
_menuView.hidden = YES;
_gameView.hidden = YES;
_stickerView.hidden = YES;
}
So now we have our UIWindow view which contains our views and also our keyboard. They are all hidden so our keyboard appears at the front and can be typed on.
Now use a simple function to decide which view to bring in front of the keyboard:
- (void)bringViewToFront: (UIView *)view {
[self hideViews];
view.hidden = NO;
}
Hiding the views makes sure we only have our correct view at the front.
I spent a lot of time thinking how we could move different views forward and back, using the exchange function. Actually using hide and reveal means we can get our view immediately and still easily have access to the keyboard by hiding all the views.