Beginner's Guide
Steven F. Daniel
Chapter No. 6
"Displaying Notification Messages"
These types of applica ons enable users to work with data, play games, or communicate
with other users. Despite these, at some point an applica on will need to communicate with
the user. This can be as simple as a warning message, or providing feedback or even asking
the user to provide some informa on.
The iPhone and Cocoa-Touch use three special methods to gain your a en on and are
explained below:
CLASS
UIAlertView
DESCRIPTION
This class creates a simple modal alert window that presents the
user with a message and a few op ons.
Modal elements require the user to interact with them before
they can proceed. These types of elements are displayed (layered)
on top of other windows and block the underlying objects un l
the user responds to one of the ac ons presented.
UIActionSheet
Generating alerts
There is no doubt that you will need to incorporate alerts into your applica ons. These can
be very useful to inform the user of when the applica on is running, and can be a simple
message such as memory running low, or that an applica on or internal error has occurred.
We can no fy the user in a number of ways using the UIAlertView class, and it can be used
to display a simple modal message or gather informa on from the user.
[ 202 ]
Chapter 6
1.
Select the View-based applica on template from the project template dialog box.
2.
Ensure that you have selected iPhone from under the Device Family dropdown, as
the type of view to create.
3.
4.
Enter GetUsersA en on and then choose a loca on where you would like to save
the project.
Once your project has been created, you will be presented with the Xcode interface, along
with the project files that the template created for you within the Project Navigator Window.
1.
2.
Then select your project target from under the TARGETS group.
3.
4.
5.
Then finally, use the + bu on to add the library that you want to add; if you want to
remove a framework, highlight it from the group and click on the - bu on. You can
also search for the framework if you can't find it in the list shown.
[ 203 ]
If you are s ll confused on how to go about adding these frameworks, refer to the following
image, which highlights what parts you need to select (highlighted by a red rectangle):
CoreAudio
[ 204 ]
Chapter 6
MediaPlayer
d. AudioToolbox
3.
Under which tab is the Link Binary with Libraries sec on located?
a. Build Se ngs
b. Build Rules
c.
Summary
d. Build Phases
1.
From the Object Library, select and drag a (UIBu on) Round Rect Bu on control
onto our view. Modify the Object A ributes of the Round Rect Bu on control and
set its tle to read "Show Ac vity Indicator".
2.
From the Object Library, select and drag a (UIBu on) Round Rect Bu on control
onto our view. Modify the Object A ributes of the Round Rect Bu on control and
set its tle to read "Display Alert Dialog".
[ 205 ]
3.
From the Object Library, select and drag a (UIBu on) Round Rect Bu on control
onto our view. Modify the Object A ributes of the Round Rect Bu on control and
set its tle to read "Display Ac on Sheet".
4.
From the Object Library, select and drag a (UIBu on) Round Rect Bu on control
onto our view. Modify the Object A ributes of the Round Rect Bu on control and
set its tle to read "Play Alert Sound".
5.
From the Object Library, select and drag a (UIBu on) Round Rect Bu on control
onto our view. Modify the Object A ributes of the Round Rect Bu on control and
set its tle to read "Vibrate iPhone".
If you have followed everything correctly, your view should look something like the following
screenshot. If it doesn't look quite the same, feel free to adjust yours:
[ 206 ]
Chapter 6
Creating events
Now that we have created our user interface, we need to create the events that will respond
when we click on each of the bu ons. If you need to refresh your memory on how to go
about this, you can refer to the sec on Making our Components work together in Chapter 3,
Introducing Interface Builder.
We first need to create an instance of our UIAlertView class, called baseAlert, which will
be used by our Show Ac vity indicator event and will be used to dismiss the ac vity a er a
period of me has lapsed.
Open the GetUsersAttentionViewController.h interface file and add the following
highlighted code as shown in the code snippet below:
#import <UIKit/UIKit.h>
@interface GetUsersAttentionViewController : UIViewController
<UIAlertViewDelegate, UIActionSheetDelegate>{
UIAlertView *baseAlert;
}
@end
[ 207 ]
The default size of the Ac vity indicator is a 21-pixel square, but can be changed to 36-pixels
by using the UIActivityIndicatorViewStyleWhiteLarge style. In this sec on, we will
look at how to go about implemen ng this class, combined with the UIAlertView control:
1.
2.
In the ac on event which you created for the Show Ac vity Indicator bu on, add
the following code:
// Displays our progress indicator with a message
- (IBAction)showProgress:(id)sender {
// initialize our Alert View window without any buttons
baseAlert=[[[UIAlertView alloc]initWithTitle:@"Please
wait,\ndownloading updates.." message:nil delegate:self
cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
// Display our Progress Activity view
[baseAlert show];
// create and add the UIActivity Indicator
UIActivityIndicatorView
*activityIndicator=[[UIActivityIndicatorView
alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyl
eWhiteLarge];
activityIndicator.center=CGPointMake(baseAlert.bounds.size.width
/ 2.0f,baseAlert.bounds.size.height-40.0f);
// initialize to tell our activity to start animating.
[activityIndicator startAnimating];
[baseAlert addSubview:activityIndicator];
[activityIndicator release];
// automatically close our window after 3 seconds has passed.
[self performSelector:@selector(showProgressDismiss)
withObject:nil afterDelay:3.0f];
}
3.
Next, we need to create an event to dismiss the progress indicator. Create the
following showProgressDismiss event and add the following code:
// Delegate to dismiss our Activity indicator after the number of
seconds has passed.
- (void) showProgressDismiss
{
[baseAlert dismissWithClickedButtonIndex:0 animated:NO];
}
[ 208 ]
Chapter 6
3. Finally, set up a delay and create a new method to dismiss the ac vity indicator a er
a delay of five seconds has passed. You can refer to the sec on Implemen ng the
Show Ac vity Indicator located in this chapter.
Once you have that working, you will have mastered how to create an applica on that
contains more than one form of no fica on to grab the user's a en on. This lets the user
know that updates are being finalized.
stopAnima ng
hideWhenStopped
1.
2.
In the ac on event which you created for the Display Alert Dialog bu on, add the
following code:
// Handles of the setting up and displaying of our Alert View
Dialog
- (IBAction)displayAlertDialog:(id)sender {
// Declare an instance of our Alert View dialog
[ 210 ]
Chapter 6
UIAlertView *dialog;
// Initialise our Alert View Window with options
dialog =[[UIAlertView alloc] initWithTitle:@"Alert Message"
message:@"Have I got your attention" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
// display our dialog and free the memory allocated by our
dialog box
[dialog show];
[dialog release];
}
DESCRIPTION
message
This property sets the string that will appear within the content area
of the alert dialog box.
delegate
Contains the object that will serve as the delegate to the alert.
Ini alizes the view and sets the tle that will be displayed at the top
of the alert dialog box.
If this is set to nil, then no ac ons will be performed when the user
dismisses the alert.
cancelButtonTitle
This sets the string shown in the default bu on for the alert.
OtherButtonTitles
Adds addi onal bu ons to the sheet that are delimited by commas
as shown:
otherBu onTitles:@"Out to Lunch",@"Back in 5 Minutes",@"Gone
Fishing".
In the above code snippet, we declared a delegate method which handles the bu on presses
and retrieves the index of the bu on which was pressed. We declare an NSString variable
bu onText, which will be used to store the tle text to be displayed by our UIAlertView.
In order to determine the index of the bu on which was pressed, we perform a switch
statement and then set up the bu onText variable with the associated text. Finally, we
declare and instan ate a UIAlertView object, which will be used to display the gree ng
for the bu on which was pressed. We then display the dialog and then finally release the
memory used.
[ 212 ]
Chapter 6
Finally, we looked at another way in which we can derive what bu on has been pressed.
We declare an object NSString bu onTitle, which retrieves the text label for the bu on
pressed on the ac on sheet. We then use the isEqualToString method to perform
the comparison.
otherButtonTitles
[ 213 ]
The tle of the op on that will result in the informa on being lost.
1.
2.
In the ac on event which you created for the Display Ac on Sheet bu on, add the
following code:
// Displays our Action Sheet
- (IBAction)displayActionSheet:(id)sender {
// Define an instance of our Action Sheet
UIActionSheet *actionSheet;
// Initialise our Action Sheet with options
actionSheet=[[UIActionSheet alloc]initWithTitle:@"Available
Actions" delegate:self cancelButtonTitle:@"Cancel"
destructiveButtonTitle:@"Close" otherButtonTitles:@"Open
File",@"Print",@"Email", nil];
// Set our Action Sheet Style and then display it to our view
actionSheet.actionSheetStyle=UIBarStyleBlackTranslucent;
[actionSheet showInView:self.view];
}
[ 214 ]
Chapter 6
DESCRIPTION
delegate
Contains the object that will serve as the delegate to the sheet.
cancelButtonTitle
This sets the string shown in the default bu on for the alert.
destructiveButtonTitle
OtherButtonTitles
[ 215 ]
Create the following delegate func on located under the displayActionSheet method:
// Delegate which handles the processing of the option buttons selected
-(void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex
{
// String will be used to hold the text chosen for the button
pressed.
NSString *buttonText;
// Determine what button has been selected.
switch (buttonIndex)
{
case 0: // We selected the Close button
buttonText=@"You clicked on the 'Close' button";
break;
case 1: // We selected the Open File button
buttonText=@"You clicked on the 'Open File' button";
break;
case 2: // We selected the Print button
buttonText=@"You clicked on the 'Print' button";
break;
case 3: // We selected the Email button
buttonText=@"You clicked on the 'Email' button";
break;
case 4: // We selected the Cancel button
buttonText=@"You clicked on the 'Cancel' button";
break;
default: // Handle invalid button presses.
buttonText=@"Invalid button pressed.";
}
// Initialise our Alert Window
UIAlertView *dialog=[[UIAlertView alloc] initWithTitle:@"Alert
Message" message:buttonText delegate:nil cancelButtonTitle:@"OK"
otherButtonTitles:nil,nil];
// display our dialog and free the memory allocated by our dialog
box
[dialog show];
[dialog release];
}
In the above code snippet, we declare a delegate method which handles the bu on presses
and retrieves the index of the bu on which was pressed based on the order in which they
were added. We declare an NSString variable bu onText which will be used to store the
tle text to display by our UIAlertView. In order to determine the index of the bu on
which was pressed, we perform a switch statement and then set up the bu onText variable
with the associated text. Finally, we declare and instan ate a UIAlertView object which
will be used to display the gree ng for the bu on which was pressed. We then display the
dialog and then finally release the memory used.
[ 216 ]
Chapter 6
Just in the same way as we did for alerts, if you want to retrieve the selected bu on using its
text property, we would do so as shown in the following code snippet:
NSString *buttonTitle=[actionSheet buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:@"Close"])
{
buttonText=@"You clicked on the 'Close' button";
}
In the above code snippet, we looked at an alterna ve way by which we can derive what
bu on has been pressed. We declared an object NSString bu onTitle, which retrieves the
text label for the bu on pressed on the ac on sheet. We then used the isEqualToString
method to perform the comparison.
This code renders the ac on sheet in a translucent black style. If you wanted to inherit the
style of the views toolbar provided to which you have applied a style, you could use the
UIActionSheetStyleAutomatic or if you preferred to go for a more solid-black classy
finish, you could use and apply the UIActionSheetStyleBlackOpaque style:
1.
[ 217 ]
2.
Our next step is to implement our playAlertSound method. This method will be
responsible for playing a short 30 second sound when the Play Alert Sound bu on is
pressed. In the ac on event which you created for the Play Alert Sound bu on, add
the following code:
// Plays an Alert Sound
- (IBAction)playAlertSound:(id)sender {
SystemSoundID soundID;
NSString *soundFile = [[NSBundle
mainBundle]pathForResource:@"Teleport" ofType:@"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL
fileURLWithPath:soundFile],&soundID);
AudioServicesPlaySystemSound(soundID);
}
3.
Our next step is to implement our vibratePhone method. This method will
be responsible for making our phone vibrate when the Vibrate iPhone bu on is
pressed. Enabling the ability to provide feedback via vibra on is a very simple and
painless technique and all that is required is to pass a System Sound ID value to the
AudioServicesPlaySystemSound method as we will see in a minute.
4.
In the ac on event which you created for the Vibrate iPhone bu on, add the
following highlighted code:
- (IBAction)vibratePhone:(id)sender {
AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
}
Now that we have finally created the necessary methods within our applica on to
enable us to play sounds and vibra ons, our next step is to build our applica on, as
shown below.
5.
We are now ready to build and compile our GetUsersA en on applica on.
The screenshot below shows the output from each of the bu ons when they
are pressed:
[ 218 ]
Chapter 6
So there you have it. We have explored five dierent ways in which we can communicate
eec vely with the user. By implemen ng these methods into your own applica ons, you
will not only make your applica on more user-friendly, but it will also look more professional.
Once we have set up our SoundID properly, all that is required is to play the sound which
is achieved by passing the SoundID variable to the AudioServicesPlaySystemSound
method.
We finally passed the kSystemSoundID_Vibrate constant variable to our
AudioServicesPlaySystemSound method to allow our device to handle
vibra ons which have been defined within the AudioToolBox.h header file.
Chapter 6
Summary
In this chapter, we learned about the dierent types of no fica on methods and modal
dialogs which we can use to communicate eec vely with the user.
We also learned how to go about using alerts and Ac on sheets and how to set the UI
appearance of the Ac on Sheet using its various styles.
We finally looked at the two non-visual means by which we can communicate with the user
by using sounds and vibra ons using the AudioToolBox framework. Simply by using this
framework, you make your applica ons more exci ng and easily add short playing sounds
and vibrate the iPhone.
Now that we have learned about the various ways in which you can communicate with
the user, through alerts and ac on sheets, and sounds and vibra on; we are ready to start
focusing on how to handle the iPhone Mul Touch Architecture and learn how we can
detect swipes, taps, pinches, and shaking. We will also be looking into the new iPhone 4
orienta ons by using the gyroscope feature. All of this will be covered in the next chapter.
[ 221 ]
Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and
most internet book retailers.
www.PacktPub.com