NSStatusItem to be always left? - objective-c

I'm working on an app that displays certain information on the status menu, and I was wondering if there's any Cocoa API that can make my NSStatusItem always placed on the most-left, no matter when it's started or if other apps are started after it.
NSStatusBar *bar = [NSStatusBar systemStatusBar];
barItem = [[bar statusItemWithLength:NSVariableStatusItemLength] retain];
Thanks.

Taking you ultra-literally for a moment, what if two applications used such an API? They would fight and roll off the end of the menu bar. ☺
There is no supported way to do it, but there is an undocumented/unsupported way to specify the “priority” of the status item when you create it. Of course, use at your own risk, and be sure to do a respondsToSelector: check to fall back on the supported way if the unsupported way goes away.

Related

Catch key events in a NSWindow

I'm trying to get a very basic web browser with 3 Webviews (2 hidden and 1 visible at all times).
I'd like to switch between these 3 webviews by pressing CMD+1, CMD+2, CMD+3.
I have created a basic Cocoa app, added 3 webviews in it, referenced the Webkit framework and I'm up and running with it, this part is working.
Now I wonder:
1) How to catch key event? It seems so overly complicated that browsing the event structure docs gave me a headache.
[rant]From someone who did lots of Windows forms, GTK, QT and Java/C#/C++ work it seems that XCode is getting worse every release by moving everything around and creating 3 different ways of achieving the same thing, etc. Each time I have to use it's always like I have to learn everything once again.[/rant]
2) How to specifically catch CMD+NUMBERS ?
This is just for a quick productivity app I'm building to use in conjunction with JIRA (project management).
I'd appreciate if somebody could point me in the good direction.
Every time I stumble upon a good tutorial, it was outdated or was for iOS dev which most of the time doesn't use the same APIs as OS X anymore.
Sorry about the rant and thanks about your help!
What you are looking to override is the NSResponder method "keyDown:", and what I would recommend doing is subclassing "WebView" and create your own "keyDown" method (make certain to call "[super keyDown: theEvent]" somewhere in your implementation, though).
Now, within your "keyDown" implementation, to look for the command key, "NSEvent" objects respond to the "modifierFlags" method and one of the flags is "NSCommandKeyMask".
E.G.:
NSUInteger flags = [theEvent modifierFlags];
if( flags == NSCommandKeyMask ){
// Got it!
}
Don't worry about what kind of views they are.
Put each one inside a tab of an NSTabView, with or without tab control displayed.
With tab control, set the desired key combo per tab in IB.
With or without it, create a menu item in a menu in the menu bar for each tab with the same key combos. This is the recommended way since long ago. Apple recommends adding a menu bar menu item for everything that has a keyboard shortcut. The menu bar will receive the keys before anything else.

How to add the iOS "Open In..." feature to an app

I would like to know how to present the "Open In..." Action Sheet (iPhone) / Popover (iPad) from my app, preferably an IBAction
I would hope that it'd be similar to declaring a file type then creating the view and opening the app selected by the user, but I know it is more complicated then that.
I realize that a similar question has been asked on StackOverflow, but I cannot make sense of the answer that was accepted: How to use "open in..." feature to iOS app?, and I have found some Apple Documentation on Document Interaction Programming. But, I can't really make sense of these.
Create a UIDocumentInteractionController by using the interactionControllerWithURL: class method (pass the URL of the file you want to open in another app).
Then call either presentOpenInMenuFromRect:inView:animated: or presentOpenInMenuFromBarButtonItem:animated:. The controller takes care of presenting the popover with available apps for that file type and opening the selected app.
If you want to know when the menu was dismissed and which app was selected, you need to implement the UIDocumentInteractionControllerDelegate protocol.
omz makes some good points on how to do that in his answer, however this procedure is much easier with the introduction of new APIs in iOS 6. Here's a simple and efficient way to show the UIActionSheet Open-In-Menu in iOS 6 and up:
NSArray *dataToShare = #[contentData]; //Or whatever data you want to share - does not need to be an NSArray
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:nil];
Also, if your app is compatible with versions of iOS lower than 6.0 you may want to check if the Share Service exists:
if ([UIActivityViewController class])
Once you present the sheet, iOS will automatically handle the rest for you. It will display a beautiful uiactionsheet with icons showing each app or service the user can open / share your data with:
Note that depending on the contents of the data, iOS will show different services in the Share Sheet
EDIT: The method above shares the file content, but not the file itself. Refer to omz's answer for more on that.
I've personally never had to do this, but your answer can most certainly be found in this Apple Documentation: http://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/PreviewingandOpeningItems.html#//apple_ref/doc/uid/TP40010410-SW1.

Cocoa Message with no action required

I'm trying to figure out a way to give a user feedback when they have saved settings. similar to Microsoft's "File Saved" dialog Is there a class for this type of dialog? I do not want to require any action by the user. Just "Your setting have been saved" then disappears after a short delay. Maybe a better way to describe would be like a jQuery message box with a fade in fade out type thing
Is there a class for this type of dialog?
That isn't a "dialog", because you're not accepting input from the user. At best, it's an alert, and you could therefore use NSAlert (see also "Dialogs and Special Panels") however, what you are contemplating is contrary to the recommendations given in the HIG for "Alerts":
Avoid using an alert merely to give users information. Although it’s important to tell users about serious problems, such as the potential for data loss, users don’t appreciate being interrupted by alerts that are informative but not actionable. Instead of displaying an alert that merely informs, give users the information in another way, such as in an altered status indicator.
In other words, this probably wouldn't be considered a good user experience by the OS X-using population.
You can still do this, if you absolutely must, by creating a sheet or alert window and setting a timer to dismiss it.
A much better plan would be to have a label somewhere in your interface whose text could display this information, again using a timer to clear the notice after an appropriate duration.
Yet another option (possibly the best) would be to put this notice somewhere that the user only sees it upon request. The HIG mentions Mail.app's information area at the bottom of its sidebar, for example.
It is simple to fade a window in and out using the NSViewAnimation see also NSAnimation Class
An example I use something like this.
- (void)fadeWindowIn{
//--make sure the window starts from 0 alpha. Or you may get it jumping in view then try and fade in.
[theWindow setAlphaValue:0.0];
//-- set up the dictionary for the animation options
NSDictionary *dictIn = [NSDictionary dictionaryWithObjectsAndKeys:
theWindow,NSViewAnimationTargetKey,
NSViewAnimationFadeInEffect,NSViewAnimationEffectKey,nil];
NSViewAnimation * fadeWindowIntAnim = [[[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dictIn]] autorelease];
[fadeWindowIntAnim setAnimationCurve:NSAnimationLinear];
[fadeWindowIntAnim setDuration:2];
[fadeWindowIntAnim setFrameRate:20.0];
//--start the animation
[fadeWindowIntAnim startAnimation];
//--set the timer for the fade out animation
[NSTimer scheduledTimerWithTimeInterval:4.8 target:self selector:#selector(fadeWindowOut) userInfo:nil repeats:NO];
}
-(void)fadeWindowOut{
//-- fade the window.
NSDictionary *dictOut = [NSDictionary dictionaryWithObjectsAndKeys:
theWindow,NSViewAnimationTargetKey,
NSViewAnimationFadeOutEffect,NSViewAnimationEffectKey,nil];
NSViewAnimation * fadeOutAnim = [[[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dictOut]] autorelease];
[fadeOutAnim setAnimationCurve:NSAnimationLinear];
[fadeOutAnim setDuration:1.2];
[fadeOutAnim setFrameRate:20.0];
[fadeOutAnim startAnimation];
}
theWindow is the NSWindow or NSView you want to fade in and out. Read the references to understand the options.
You can create your own such popup (using NSTimer to dismiss as needed), but perhaps an easier way would be to use the existing third-party library at http://code.google.com/p/toast-notifications-ios/. This library emulates Android's "toast" functionality.
Note that this library is for iOS development (not OSX), but wasn't sure which platform you were planning to target. Regardless, it should be adaptable with a little work.
The other answers about timers and such cover that aspect of it pretty well. I just wanted to jump in and suggest you take a look at the Growl framework. This seems to be the preferred way to do this sort of passive notification until Apple builds it into the OS.
Among other things, it gives the user a lot of control over how the notifications look, where they live on the screen, how long they stay up, and which apps are even allowed to display them. And they do this without you having to write any code. The downside is that it's another thing for your users to have to install, which could be a deal breaker for your app.
They also recently moved into the App Store and started charging a nominal fee ($2 or $3, I think) which could be seen as a downside but I think of it as a more positive thing: users will have a much easier time installing it now.
Some apps that make use of Growl notifications include BBEdit, Transmission, Scrivener, Twitteriffic, etc. Which is to say that it's not a fly-by-night thing.
As a user, I hate it when apps try to roll their own notifications since I lose all of the control that I get with Growl.
Just a thought, anyway.

Can anyone help out an Objective C novice?

I feel i am totally out of my depth here, im very new to objective c but have been asked to design an iphone app as part of my uni course. I designed a sinple quiz before, but I was hoping to design a more advanced quiz game with 3 levels (each level will have a different quiz).
I dont know how to use the UIViews and I have tried a tutorial online to help me code a navigation controller. It allows gives me 3 options to go into subview 1, 2 or 3. All the subviews have the same screen though, with one label and a button.
I have 3 classes so far, RootViewController, BasicNavigationAppDelegate and SubViewOneController.
I really dont understand the code at all, im familiar with Java but this objective c is nothing like it. Could someone maybe take a minute to help out a person in distress and explain if i am doing this right by using the navigation controller to display my levels? When i check the xib interface files i dont see the button or label, or dont know where to add the quiz interface objects!! I really am confused by all this. Could anyone help?
You should search google for sample source code, and see how some of the views can be handled. There are many ways you can handle a view, whether its by a UINavigationController, UITabBarController, etc. If you are new to Objective-C, then your not really going to get an answer to this question that will instruct you on what exactly to do.
Interface Builder + View Controllers
Here's a good one for you: View Controllers Programming Guide
(Apple's) View Controller Reference Guide
Some Code Samples
Getting Started Sample Code
I recommend Head First iPhone Development: A Learner's Guide to Creating Objective-C Applications for the iPhone. Within a few chapters you'll know everything you need to build this app and you'll actually understand what you're doing.
(I don't know the authors or the publisher, I just think it's a great book for quickly getting up to speed.)
for a 3 level quiz, UINavigationController is definitely an option.
if you need to find out how to use a class, in xcode, type its name, then press -alt- and double click the class name, this will bring up a short description, with two icons, one will take you to the header file, and the other to the documentation.
to add elements to the nib/xib files, you will need to open the library window, where you will find labels, buttons etc. to use a button, you will need to define an action in your header file, and hook it up in IB, to be able to interact with UIElements in your code, you want to set up outlets in the header file, and hook them up in IB.
something you need to decide on, is how you are going to present the questions, and will also depend if the answer will be true/false, multiple choice, or text entry.
if you arent familiar with obj-c and xcode, it is probably worth picking up an ebook from someone like http://www.pragprog.com. they have an iPhone one up there by Bill Dudney which is quite good(i believe he now works for apple.)
for the standard slide out transition you could use this.
//you would probably want to call this something like level1NavBarItemWasPushed: instead
- (IBAction)lvl1pushNavBarItem:(id)sender {
//create instance of AnswersViewController class.
AnswersViewController *level1AnswersVC= [[Level1AnswersViewController alloc] init];
//pass it some kind of identifier so it can tell which quiz/question it is dealing with and pull in the answers, so that you can reuse the view
[level1AnswersVC setAnswersObject:<<insert object dictionary here>>];
//push the view controller onto the navigationController's view stack
[self.navigationController pushViewController:level1AnswersVC animated:TRUE];
//pushing it onto the view stack has given it +1 retain, so we can now release it without worrying about it disappearing prematurely.
[level1AnswersVC release];
}
for the page flip transition you could use this.
- (IBAction)lvl1pushNavBarItem:(id)sender {
//create instance of AnswersViewController class.
AnswersViewController *level1AnswersVC= [[Level1AnswersViewController alloc] init];
//pass it some kind of identifier so it can tell which quiz/question it is dealing with and pull in the answers, so that you can reuse the view
[level1AnswersVC setAnswersObject:<<insert object dictionary here>>];
//set the current viewController as the delegate, so that it can call back to us when its done
level1AnswersVC.delegate = self;
//set the modal transition style
level1AnswersVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//show answers as modal view, which has been setup to use the page flip transition.
[self presentModalViewController:level1AnswersVC animated:YES];
//pushing it onto the view stack has given it +1 retain, so we can now release it without worrying about it disappearing prematurely.
[level1AnswersVC release];
}

Is using subviews in Alert undocumented

I have asked a similar question here and got some answers, so first of all sorry for making you people bother once again.
But I have an argument this time. First I will show my piece of code
- (void) showTheAlert{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Hey!" message:#"?" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Yes",#"No",#"Don't know eaxactly.",nil];
[alertView setTag:101];
[alertView show];
}
- (void)willPresentAlertView:(UIAlertView *)alertView{
if(alertView.tag == 101){
[[[alertView subviews] objectAtIndex:2] setBackgroundColor:[UIColor colorWithRed:0.5 green:0.0f blue:0.0f alpha:0.5f]];
[[[alertView subviews] objectAtIndex:3] setBackgroundColor:[UIColor colorWithRed:0.0 green:0.5f blue:0.0f alpha:0.5f]];
}
}
And my final alert looks like
Now my confusion is that, [alertView subviews] is not documented as some people may say but alertview is a subclass of UIView, which has a property called subviews.
So I am using the documented property of a superclass which is definitely allowed.
So if this alertview may cause rejection of my app or not? ( I don't think apple will have any base to say I am using the undocumented or a private api. The look and feel is also alike to alertview.)
Apples iPhone Human Interface Guidelines about alert views clearly states:
The infrequency with which alerts appear helps users take them seriously. Be sure to > minimize the number of alerts your application displays and ensure that each one offers > critical information and useful choices. In general, try to avoid creating alerts that:
Update users on tasks that are
progressing normally.
Instead, consider using a progress
view or an activity indicator to
provide progress-related feedback to
users (these controls are described
in “Progress Views” and “Activity
Indicators”).
Ask for confirmation of
user-initiated actions.To get confirmation for an action the user initiated, even a potentially risky action such as deleting a contact, you should use an action sheet (described next in “Using Action Sheets”).
Inform users of errors or problems
about which they can do nothing.
Although it might be necessary to use an alert to tell users about a
critical problem they can’t fix, it’s
better to integrate such information
into the user interface, if possible.
For example, instead of telling users
every time a server connection fails,
display the time of the last
successful connection.
So, my advice, the time waiting for a potential rejection isn't worth your time. Don't risk it.
To follow on Henrik's reply, in the iPhone Human Interface Guidelines section "Designing an Alert", they say the following:
Although you can choose the number of
buttons to place in an alert, a
two-button alert is often the most
useful, because it is easiest for
users to choose between two
alternatives. It is rarely a good idea
to display an alert with a single
button because such an alert cannot
give users any control over the
situation; instead, it can only
display information and provide a
dismiss button. An alert that contains
three or more buttons is significantly
more complex than a two-button alert,
and should be avoided if possible. In
fact, if you find that you need to
offer users more than two choices, you
should consider using an action sheet
instead (see “Using Action Sheets” and
“Designing an Action Sheet” for more
information on this type of view).
Because users sometimes respond to
alerts without reading them carefully,
be sure to provide an appropriate
default choice. To help guide
inattentive users towards this choice,
make the light-colored, right-hand
button the safe, default alternative.
For example, you might choose to make
this button the Cancel button, to help
users avoid inadvertently causing a
dangerous action, or you might make it
represent the most common response, if
the resulting action isn’t
destructive.
The following guidelines describe how
buttons are configured in an alert:
In an alert with two buttons, the button on the left is always
dark-colored and the button on the
right is never dark-colored.
In a two-button alert that proposes a potentially risky action, the button
that cancels the action should be on
the right and light-colored.
In a two-button alert that proposes a benign action, the button that
cancels the action should be on the
left (and therefore dark-colored).
In an alert with a single button, the button is light-colored.
You are clearly violating the guidelines in size, shape, number, and color of the buttons in your alert view (red has a very clear meaning as a destructive action, not a confirmation). Even if Apple doesn't reject your application in review (which they tend to do for clear violations of the Human Interface Guidelines), this would be extremely confusing to your users.
Also, navigating the hidden view hierarchy for any Apple-supplied user interface element is a very bad practice. The view hierarchies are undocumented, and do change often. Many of the applications that started crashing when people upgraded to iPhone OS 3.0 did so because those applications did something funky with subviews of UI elements, and those elements changed in the new OS version. Apple even specifically called this out in the iPhone OS 3.0 migration documents (which I can't find now).
Because of the problems this caused, they appear to have cracked down on this practice and have been rejecting applications because of it. Even if they don't, it shows contempt for your users if you do this, because it means that you don't care if your application breaks with future OS upgrade.
I'm fairly sure altering UIAlertView by digging through the view hierarchy is a no-no. Firstly because it "uses standard iPhone screen images in a non-standard way, potentially resulting in user confusion", and secondly because if they change the view hierarchy your app is broken.
I might be wrong, I've never tried to get something like this onto the store, but my gut says don't risk it.
You can get a red button using a standard UIActionSheet, can you not?