Académique Documents
Professionnel Documents
Culture Documents
Velum Media
news
web dev
mobile dev
the cloud
networking
music
fitness
bestcovery
search
home
featured
tutorials
snippets
ipad
iphone / ipod touch
Like
21
Share
Way back when, when everyone was still complaining about Apples lack of support for (3rd party) multitasking,
there was a simple solution put in place. This solution was known as push notifications.
Push notifications solved many of the issues associated with background processing. For example, when quitting the AIM application, the server could keep you
logged in and send you a push notification when a new message arrived. You could then tap on a View button that would launch the app.
This solution is great and all, but it still requires that you have an active internet connection. As of iOS4, Apple has introduced a new type of notification that can
be scheduled to fire within the device itself. It requires no complicated server programming, or additional configuration with iTunes. I am talking about Local
Notifications.
Local notifications can be scheduled on the users iDevice to fire at any given time; you can even set them to be recurring. Today, we will explore these
notifications and I will provide you with a simple example of how to schedule, view, and handle local notifications. Here is a quick screenshot of the project that
we are going to create (note I am using the iPhone 4 simulator).
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
1/9
6/19/12
The project will allow a user to schedule a location notification to fire off at a given date. Using the text field, they are also able to specify some text for the
notification. The table view below displays a list of all of the currently scheduled location notifications within the application.
So, by now (if you are an avid iCodeBlog reader), you are already a killer iPhone dev and I can rush through the stuff that is not related to the notifications. I will
try to provide links to tutorials about sections that I rush through as well.
Seems clear enough. We have 3 UI elements that we care about and one action. One thing to note is, your class should implement the UITableViewDelegate and
UITableViewDataSource protocols. This is because we will be displaying a tableview containing all of the scheduled alarms.
Now, do all of the necessary steps in your .m file. This includes memory management for the IBOutlets and creating a dummy method for the scheduleAlarm
IBAction. Your .m file should look something like this. Note: I have omitted import statements because my syntax highlighter wasnt digging them.
@implementation NotifierViewController
@synthesize datePicker,tableview, eventText;
- (IBAction) scheduleAlarm:(id) sender {
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
2/9
6/19/12
- (void)viewDidUnload {
datePicker = nil;
tableview = nil;
eventText = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
Now its time to build our interface. Open Interface builder and construct an interface like this.
After creating the interface, make sure you hook up all of the UI components to their corresponding IBOutlets and hook up the touchUpInside: method of the
button the your scheduleAlarm: IBAction. For more info on hooking up IBOutlets, check out this tutorial.
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
3/9
6/19/12
OK, finally some real code. Most of this code should seem pretty straight forward. If not, check out this tutorial on UITableViews.
So, the new code here is dealing with retrieving a list of scheduled notifications. Calling the scheduledLocalNotifications method of UIApplication will return an
NSArray of all notifications scheduled by the current app. We just index into this array and grab each notification.
Finally, we are displaying the alertBody (text that displays when the notification fires) and the fireDate (date and time when the notification will display) in the
tableview cell.
4. Scheduling Notifications
And now for the moment youve been waiting for OK, probably not, but definitely the most exciting (least boring) part of this tutorial. Lets implement that
scheduleAlarm: IBAction that you framed out earlier. Update your .m file to contain the following code.
- (IBAction) scheduleAlarm:(id) sender {
[eventText resignFirstResponder];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = @"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
[self.tableview reloadData];
}
So, most of the explanation is in the comments. Ill talk you through some of the less obvious stuff. The first tricky area is dealing with the NSCalendar. We just
use the NSCalendar object to break up the date into components. Note: This demo does not require that we break the date up into components. You could have
just as easily fed the date from the date picker into the notification fireDate. The reason that Im showing you how to break it down is, you may have some sort of
custom date logic to work with and this makes things much easier in the future.
Another important bit of code is where we set the alertBody or the notification. In this example we set it to the text that the user entered into the text field. You can
set this to whatever you like.
The other thing I want to mention is the infoDict in the code. This dictionary is your chance to associate some additional information with the alert. For example, if
you are using this alert in a game like We Rule to notify you when a crop is ready. You might want to set a key and value that contains the id of the crop that has
completed. For now, we just set some arbitrary values and you can ignore them if you like.
After actually scheduling the notification, we just reload the tableview to get it to display immediately.
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
4/9
6/19/12
Open up your app delegate .m file and add the following code.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
[window addSubview:viewController.view];
[window makeKeyAndVisible];
application.applicationIconBadgeNumber = 0;
// Handle launching from a notification
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSLog(@"Recieved Notification %@",localNotif);
}
return YES;
}
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {
// Handle the notificaton when the app is running
NSLog(@"Recieved Notification %@",notif);
}
The first thing we see here is the application badge number is getting set to 0. Whenever a notification fires, it will increase the badge count on the application.
Next, we handle the case when the application launches from a notification. This happens when the user presses the view button on the notification. For now, we
just NSLog the data, but you should handle the notification how you see fit for your app.
Finally, we implement the didReceiveLocalNotification method. This method is required if you want to handle notifications at all in your app. You will see this
method fire when the app is running and you receive a local notification. When the app is running, you will not see the UIAlertView show up with the notification
data.
And there you have it! The complete lifecycle of a local notification. You may download the source for this tutorial below. If you have any questions, feel free to
post them in the comments section or write them to me on Twitter.
Notifier Source Code
Be Sociable, Share!
Like
21
Share
Previous Post
Next Post
Popular Posts
iPhone Game Programming Tutorial - Part 1 338 comments
iPhone Programming Tutorial - Populating UITableView With An NSArray 322 comments
iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 1 225 comments
iPhone Programming Tutorial - Connecting Code to An Interface Builder View 210 comments
iPhone Programming Tutorial - Transitioning Between Views 209 comments
WorkoutoftheDay
Strength & Conditioning Workout of the Day
Strength & Conditioning: Week 1, Day 1
Our first week of workouts from
Featured Coach Jeff Tucker. Work on
basic gymnastics skills and improve overall
Awake & Evolve Workout of the Day
strength and athleticism with this three week
Forward Bend Flow
cycle.
Relax and renew with this seated
sequence to open the hips, relax the
spine, and calm the mind with a deep forward
Women's Workout of the Day
bend.
Women's Workout: Week 9, Day 1
This 12-week cycle of the Womens
WOD will focus on building all over body
strength, as well as flexibility and core
RKC Kettlebell Workout of the Day
stabilization.
RKC Kettlebell: Week 7, Day 2
Gain strength, improve mobility, and
increase endurance in the first cycle of
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
5/9
6/19/12
categories
tags
Uncategorized
Tutorials
Snippets
Featured
Articles
Intermediate
beginner
iphone
iphone programming
iPhone Coding
Advanced
tutorial
xcode
uitableview
iOS
Partners
Bestcovery MXDWN RubyGlob SmallCloudBuilder SmallNetBuilder TGDaily
Bestcovery
Best LED TV
Best AV Receiver
Best dSLR
Best Netbook
Best Wireless Router
recent tutorials
view all beginner tutorials
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
6/9
6/19/12
Like
11
Share
READ MORE
Like
Share
READ MORE
Like
Share
READ MORE
Like
14
Share
READ MORE
Like
Share
READ MORE
view all intermediate tutorials
Like
10
Share
READ MORE
Like
Share
READ MORE
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
7/9
6/19/12
Often times you find yourself in a situation where you might want to control your application remotely. You m
Be Sociable, Share!
Like
Share
READ MORE
Like
Share
READ MORE
Like
Share
READ MORE
view all advanced tutorials
Like
Share
READ MORE
Grand Central Dispatch And Writing Methods That Accept Blocks As Arguments
Have you ever looked at the enumerateObjectsUsingBlock method of NSArray and wondered how you might use that d
Be Sociable, Share!
Like
Share
READ MORE
Like
Share
READ MORE
Like
29
Share
16
READ MORE
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
8/9
6/19/12
Update: ELCImagePickerController
I recently spent some time with ELCImagePickerController. For those of you whove worked with UIImageP
Be Sociable, Share!
Like
Share
READ MORE
iCodeBlog
elc technologies
2010 iCodeBlog. All rights Reserved. About iCodeBlog | Privacy Policy | Terms of Use | Advertise With Us. |
www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
9/9