Monday, July 4, 2011

Working with UILocalNotifications

In this post we will see how to work with the local notification but before beginning with the further reading I would request you to read my previous post which is a description on UILocalNotification class. 

Design Phase: We will trigger the local notification with the help a button and then we will close the application with the help of the home button and then after a few seconds the application will fire a notification in the form of the alert view.




Step 1: Open Xcode and create a window based application and add a UIViewController subclass file to it with any name MyViewController or any name of your choice so now there are two files into your project that’s the MyViewController.h and MyViewController.m.

Step 2: Add a function which we will call on the touch of the button inside the MyViewController.h file and then give the body to that function in the MyViewController.m file





-(void)Trigger_LocalNotification
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    UILocalNotification *_localNotification = [[UILocalNotification alloc]init];
    
      //setting the fire dat of the local notification
    _localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];


    //setting the time zone
    _localNotification.timeZone = [NSTimeZone defaultTimeZone];
    
    //setting the message to display
    _localNotification.alertBody = @"You are notified";
    
    //default notification sound
    _localNotification.soundName = UILocalNotificationDefaultSoundName;
    
    //displaying the badge number
    _localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication]applicationIconBadgeNumber]+1;
    
    //schedule a notification at its specified time with the help of the app delegate
    [[UIApplication sharedApplication]scheduleLocalNotification:_localNotification];
    
}



Code Explanation: The first line of the code removes all the local notification from the system if they are declared. In the second line I am initializing the UILocalNotification variable and in the third line I am using the fireDate property to set the time when this local notification will trigger and as you can see that the notification will be triggered after 5 seconds.


The soundName is a property of the UILocalNotification class which is used to play a sound when the notification is triggered and when the app firing this local notification is not active then in that case a alert box will pop up with the default notification sound and the alert message is written in using the property alertBody. The last line of the code will attach this notification with the system.


Step 3: make sure to attach this function with the button touch up inside event





[btn addTarget:self action:@selector(Trigger_LocalNotification) forControlEvents:UIControlEventTouchUpInside];


Step 4: Now select the App Delegate.m file of your project and create the object of this class (MyViewController)





#import "LocalNotification_DemoAppDelegate.h"
#import "MyViewController.h"

@implementation LocalNotification_DemoAppDelegate
@synthesize window=_window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    MyViewController *obj = [[MyViewController alloc]init];
    [self.window addSubview:obj.view];
    [self.window makeKeyAndVisible];
    return YES;
}

Step 5: Run the application and when the app is launched in the simulator then quickly press the home button to see the alert box of the local notification. Here’s the view at the final output.





After you hit the button then please press the home button and after 5 seconds you will see the local notification alert box 





I hope that this post has helped you out in learning how to implement UILocalNotification, please let me know if you are having any sort of queries via comment also you may request me a tutorial by posting a comment on this link and if you want to mail me your queries then feel free to mail me at my email id which is given in my facebook badge until then happy iCoding and have a great Day.

15 comments:

  1. hi its good for beginners can you please explain how to set the notifications bAsed on Id's and cancelling the notification based on ID's ?

    ReplyDelete
  2. hey how i can play recorded sound with notification.soundName ?

    ReplyDelete
    Replies
    1. Hello Anonymous,

      I am also searching for same problem.
      Please let me know if you find any.
      Thanks in advance.

      Delete
  3. @anonymous: Sorry didn't get your query, could you elaborate this

    ReplyDelete
  4. After spending a morning trying to get my head around this, you made it click. My thanks.

    ReplyDelete
  5. Hello Sir , as we have this

    _localNotification.soundName= UILocalNotificationDefaultSoundName;

    and we can set it as _localNotification.soundName= @"(resource file name with .wav or .caf ect extensions )".. but my prob is this , i want to set

    _localNotification.soundName= document directory file temp.wav. how can i set it?

    ReplyDelete
  6. Hello i am also trying to do this
    if you get any idea then please tell me

    ReplyDelete
  7. @rahul: You have to create the sound for yourself and then assign the sound that you have created to your local notification.

    You can search google for this and you will get the solution for this.

    ReplyDelete
  8. Hi Ravi Sir,
    Thanks For the good tutorial.
    I need help to get the complete app from background to foreground instead of just AlertView when the notification fires.When notification occurs I want to open my app and show a view and continue with the app then after,instead of just showing Alert.Is it Possible?
    Please Help me.

    ReplyDelete
  9. @Milind: The application cannot directly jump from background to foreground and when you interact with the alert view of UILocalNotification then only your application will be triggered and will enter the foreground mode.

    If you register a system level nottification using NSNotificationCenter for application triggering notification and when the notification is triggered then launch the app then this can be done.

    Hope that helps.

    ReplyDelete
  10. Hi Sir,
    I have problem with this code :
    //setting the fire dat of the local notification
    _localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];

    Here i wrote,
    _localNotification.fireDate = [dateFormatter dateFromString:str];

    and str stores the alarm time as '08:44'.
    but notification fires immediately,it does not wait till 08:44.
    Please Help.
    Thanks :)

    ReplyDelete
    Replies
    1. @MJ: Hello MJ, this is not how this works, see if you have a string which stores the time and you want the notification to be triggered on that particular event then in that case what you have to do is:

      - Convert the string time into actual time and attach the time with the current date and using NSDateFormatter convert the time string into actual time.

      - Then comes into action your NSDateComponent class with the help of which you can get the hour, minutes and seconds required for notification.

      Delete
    2. Thank You.It Saved me. :)
      Can i handle action on Alert view of localNotification?

      Delete