• Steam recently changed the default privacy settings for all users. This may impact tracking. Ensure your profile has the correct settings by following the guide on our forums.

Tutorial: Implementing UIAlertViews in an iPhone Application

spike021

iPhone Developer (prev. PSP Dev)
So you want to create an alert and don't have the time to make one from scratch. How/why can you use what is already given to you? This tutorial is for teaching just that.

Prerequisites:

1. Must know basic Objective-C/Cocoa Touch
2. Have XCode and other assorted iPhone SDK tools pre-installed as this tutorial does not explain
3. Be familiar with iPhone application programming
4. Have a basic knowledge of NSTimers




UIAlertView, an Overview:

A UIAlertView, as mentioned above can be used to provide a quick alert (as is why it's named this way) but can also be used to house messages, images, controls and the like. Examples of this in action can best be explained when you double-click the home button on an iPhone/iPod Touch. This creates an Alert View that displays (if you're listening to music) the title, artist, and album of the audio file that is currently being played. Below this information is a set of four different controls:

  • Three buttons used for fast-reverse (skipping back), pause/play, and fast-forward (skipping to next track).
  • UISlider for changing audio volume.

First we will start by creating a new View Controller project from the template of the same name:

screencapture191508.jpg

I will be naming my project "Alert," but yours can be named differently if preferred -- although, it is best to use the same as to not get confused by file names and code. First we will be creating an UIAlertView to open immediately at application launch.

Start by navigating into the file labeled AlertAppDelegate.h. Any specific function that is needed and requires a delegate must have it declared within the line:

[HIGHLIGHT=objc]@interface AlertAppDelegate : NSObject <UIApplicationDelegate> { [/HIGHLIGHT]

Since we will definitely be using it inside the delegate for this particular tutorial, you must add in the keyword, UIAlertViewDelegate beside UIApplicationDelegate. But here's the trick: you must have one comma and a space after UIApplicationDelegate for this to not attract an undesired warning/error during build process/runtime. - The desired result should look like this:

[HIGHLIGHT=objc]@interface AlertAppDelegate : NSObject <UIApplicationDelegate, UIAlertViewDelegate> { [/HIGHLIGHT]

That's it for this file, now let's head over to the AlertAppDelegate.m file.

Once you have opened it, you should see the applicationDidFinishLaunching: method. For those who may not know (although you should as per the prerequisites list at top) applicationDidFinishLaunching: can be used to set up anything from music/audio to AlertViews (as we are doing) to begin/open immediately at launch (although after the Default.PNG is displayed).

The way that I usually set up the message of my Alert is as follows:

[HIGHLIGHT=objc]NSString *msg = @"Message goes inside quotes (make sure quotes aren't removed)";[/HIGHLIGHT]

This allows you to be able to use the same message multiple times without the need to copy/paste over and over again by storing it within an NSString.

[HIGHLIGHT=objc]UIAlertView *alert = [[UIAlertView alloc]

initWithTitle:@"Here you can insert a title, if desired"

message:msg // remember the NSString from before?

delegate:self

cancelButtonTitle:@"Ok" /* There are a couple different types of buttons that can be used within an Alert - 'cancel' and 'other' - cancel is used to simply close the window, with no harm done - other is used when there is a particular function/action that you would like to activate */

otherButtonTitles:nil];

[alert show]; // this is the equivalent of adding a subView, but Apple uses show since it's already been precoded into UIKit

[alert release];
[/HIGHLIGHT]

Make sure to put this code below [window addSubview:myViewController.view]; - and - [window makeKeyAndVisible];

The end result should look something like this:

[HIGHLIGHT=objc]- (void)applicationDidFinishLaunching:(UIApplication *)application {

// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];

NSString *msg = @"This is my first alert!";

UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"ZOMG!"
message:msg
delegate:self
cancelButtonTitle:@"Fine, I'm done!"
otherButtonTitles:@"I'm not done!", nil];
[alert show];
[alert release];

}[/HIGHLIGHT]

I'd like to encourage you to now try building and running it via either the simulator or device (your choice!). As long as there weren't any nasty errors, an alert view should pop up promptly.

Here's a little something extra for all you official developers! (although anyone can use it and it isn't specific to this task)

If you ever discover that your application has been cracked, there have been some far-fetched ideas about annoying the heck out of the crackers. All that's needed is an alert that just won't stop popping up. This is a somewhat good idea since the average cracked app user won't be able to stop the timer from validating.

First click on UIViewController.m. Here you should see most of the basic, Apple included methods commented out but readily available for you to override. Go ahead and delete the comment initiators and destructors stationed around the method named viewDidLoad:

We will need to add a single line into this method:

[HIGHLIGHT=objc] [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector: @selector(onTimer:)userInfo:nil repeats:YES];[/HIGHLIGHT]

There are several forms of timers available in the UIKit that you can use in your code depending on what type of action you would like to enable. If you want to simply have an action initiated every, say, 10 seconds all that is needed is a line similar to the one above. The scheduledTimerWithTimeInterval is used specifically for this task. The way that I will be implementing it in this tutorial will cause our original Alert View to reappear every 10 seconds regardless of if you have pressed one of the buttons created earlier.

Going through the line from left to right, you're setting the type of timer that you will be using when you type [NSTimer scheduledTimerWithTimeInterval]. After this, you are presented with a space for saying how long until the action is performed. The @selector should be self-explanitory if you're familiar with Objective-C/Cocoa Touch. repeats: is set to YES so that the action will always repeat... if it was set to NO, then it would only activate once as well.

And finally we have the action, named onTimer: in this example:

[HIGHLIGHT=objc]-(void) onTimer:(id)sender
{

NSString *msg = @"Bet you can't stop this timer!";

UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"ZOMG!"
message:msg
delegate:self
cancelButtonTitle:@"Fine, I'm done"
otherButtonTitles:@"I'm not done", nil];
[alert show];
[alert release];

}[/HIGHLIGHT]

Everything above should be self-explanatory as well... if not, I'd recommend going back up to the top of this tutorial and working your way through a second time. And don't worry! Take your time with this as it can be a small, but complicated task depending on it's use (although not in this tutorial).

Remember that there are multiple ways of doing this - inside Interface Builder using an IBAction connected to a UIButton, the way I just explained above, and by timer (commonly done using an NSTimer).

Final product should look something like:

screencapturel.jpg


Let me know if there are any issues at all with the tutorial since I am relatively new to writing tutorials.

Source code for this tutorial can be found here.

 
Nice tut! I wish I would have gone farther with iphone/mac development, it's really fun, but I'm sure you've figured that out already ;)
 
Nice tut! I wish I would have gone farther with iphone/mac development, it's really fun, but I'm sure you've figured that out already ;)

Thanks, it was nothing really. Yep, lot's of fun even with the few errors that lurk around once and a while.

- Stay tuned for another tutorial in the next couple days guys.
 
Back
Top