Thursday 1 October 2015

How to work with Local Notification

do some code with app delegate files:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//
//
   
    UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotification) {
        NSLog(@"Notification Body: %@",localNotification.alertBody);
        NSLog(@"%@", localNotification.userInfo);
       
  //NSString *reminderText = [localNotification.userInfo objectForKey:@"kRemindMeNotificationDataKey"];
        //[viewController showReminder:reminderText];
    }
   
    application.applicationIconBadgeNumber = 0;
}

-Then use Local NotoficationDelegate method :

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"Notification Body: %@", notification.alertBody);
    NSLog(@"%@", notification.userInfo);
   
    application.applicationIconBadgeNumber = 0;
}
//
//  MasterViewController.m
//  LocalNotification
//
//  Created by IND500 on 28/03/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MasterViewController.h"

#import "DetailViewController.h"

@implementation MasterViewController

@synthesize detailViewController = _detailViewController;

@synthesize  notificationsArray,setclear;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Master", @"Master");
    }
    return self;
}
                           
- (void)dealloc
{
    [_detailViewController release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    self.title = @"Notifications";
   
    UIBarButtonItem *addNotificationButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNotification)];
    self.navigationItem.rightBarButtonItem = addNotificationButton;
    [addNotificationButton release];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)addNotification {
   
      
    DetailViewController   *detailViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
    detailViewController.delegate = self;   
//    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:detailViewController];
    [self.navigationController pushViewController:detailViewController animated:YES];
//    [self presentModalViewController:detailViewController   animated:YES];

}




- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //reload the notifications array and table view
    self.notificationsArray = [[[UIApplication sharedApplication] scheduledLocalNotifications] mutableCopy];
    NSLog(@"%@",notificationsArray);
    [self.tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

// Clear Notification
- (void)SetClearNotification{
   
   
   
//    UIApplication *app = [UIApplication sharedApplication];
//    NSArray *eventArray = [app scheduledLocalNotifications];
//    for (int i=0; i<[eventArray count]; i++)
//    {
//        UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
//        NSDictionary *userInfoCurrent = oneEvent.userInfo;
//        NSString *uid=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:@"uid"]];
//        if ([uid isEqualToString:uidtodelete])
//        {
//            //Cancelling local notification
//            [app cancelLocalNotification:oneEvent];
//            break;
//        }
//    }  
   
   
    [notificationsArray removeAllObjects];
    [self.tableView reloadData];
   
    [self dismissModalViewControllerAnimated:YES];
}



//dismisses the modal view controller
- (void)dismissSetNotificationViewController {
   
   
    //reload the notifications array and table view
    self.notificationsArray = [[[UIApplication sharedApplication] scheduledLocalNotifications] mutableCopy];
   
    NSLog(@"%@",notificationsArray);
    [self.tableView reloadData];
   
    [self dismissModalViewControllerAnimated:YES];
  
}

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [notificationsArray count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"Cell"];

    // Configure the cell.
    UILocalNotification *notifcation = [notificationsArray objectAtIndex:indexPath.row];
   
    [[cell textLabel] setText:[notifcation alertBody]];
   
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mma"];
    [[cell detailTextLabel] setText:[dateFormatter stringFromDate:notifcation.fireDate]];
    [dateFormatter release];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.detailViewController) {
        self.detailViewController = [[[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil] autorelease];
    }
    DetailViewController   *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
   
    detailViewController.delegate = self;   
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:detailViewController];
   
    NSMutableArray *Temparr = [[NSMutableArray alloc]init];
   
    UILocalNotification *notifcation = [notificationsArray objectAtIndex:indexPath.row];
    [Temparr addObject:[notifcation alertBody]];
   
    detailViewController.reminder = Temparr;
    //[self presentModalViewController:navController animated:YES];
    [self.navigationController pushViewController:detailViewController animated:YES];
}

@end


-------------------------------------------------------------------------
- (void)addNotification {
   
   
    if(messageField.text.length>0){
       
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = self.datePicker.date;
    localNotification.alertBody = self.messageField.text;
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    localNotification.applicationIconBadgeNumber = 1;
   
        NSInteger index = [scheduleControl selectedSegmentIndex];
      //  NSLog(@"%i",index);
       
        switch (index) {
            case 1:
                localNotification.repeatInterval = NSMinuteCalendarUnit;
                break;
            case 2:
                localNotification.repeatInterval = NSHourCalendarUnit;
                break;
            case 3:
                localNotification.repeatInterval = NSDayCalendarUnit;
                break;
            case 4:
                localNotification.repeatInterval = NSWeekCalendarUnit;
                break;
            default:
                localNotification.repeatInterval = 0;
                break;
        }
   
        NSDictionary *userDict = [NSDictionary dictionaryWithObject:messageField.text
                                                             forKey:@"kRemindMeNotificationDataKey"];
        localNotification.userInfo = userDict;
       
       
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    [localNotification release];
   
           
    // calling the delegate method
        [self.navigationController popViewControllerAnimated:YES];
       
           
    }else{
       
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Somthing Wrong" message:@"Please set the title first" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
              
        [alert show];
                             
    }
   
   
}

- (void)showReminder:(NSString *)text {
   
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Reminder"
                                                        message:text delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}



- (void)cancelAddNotification {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)clearNotification {
   
    [self.delegate SetClearNotification];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

- (IBAction)dismissKeyboard {
    [self.messageField resignFirstResponder];
}