Create Interactive local notification and simple notification.

1. Create NSObject file to implement the notification functions.
2. Register the notification based on the resolutions.(iOS 7 /iOS 8 and above)
3. Separate the notification (interactive /local).
4. Cancel the notification
5. Cancel the particular notifications.
6. Handle the notification when receiving.

Create NSObject file. File named as “Notification”.

// Notification.h file

#import <Foundation/Foundation.h>

@interface Notification : NSObject

+ (Notification *) instance;   // create instance

//register the local notification to access the property
-(void) registerLocalnotification;
//create notification
-(void) setLocalnotfication:(NSDictionary *)userInfo title:
(NSString *)title date:(NSDate *)fireDate Interactive : (BOOL)flag ;
//cancel notification
-(void) cancelLocalnotifcation :(NSString *)identificationString;
-(void) cancelAllnotification ;
//handle local notifications
-(void) handleLocalnotificationActionWithIdentifier:(NSString *)identifier 
forRemoteNotification:(NSDictionary *)userInfo 
completionHandler:(void (^)()) completionHandler;



@end

#import "Notification.h"

#define UID_1 @"Action1"
#define UID_2 @"Action2"
#define NCI @"ACTIONABLE"

Notification *instanceCommon = nil;
@implementation Notification

+(Notification *) instance {
    if(!instanceCommon) instanceCommon = [[self alloc] init];
    return instanceCommon;
}

-(void)registerLocalnotification {
    
    @try {
        if([UIApplication instancesRespondToSelector:
@selector(registerUserNotificationSettings:)]) {
   // its support for 8 and above version
  //[[UIApplication sharedApplication] registerForRemoteNotifications];
    NSArray *title = [NSArray arrayWithObjects:@"Confirm",@"Again",nil];
    NSArray *identification = [NSArray arrayWithObjects:UID_1,UID_2,nil];;
    [self setRegisterInteractiveLocalnotification:identification 
titleArray:title];
            
        }
        else {
            //its support only in iOS 7
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | 
UIUserNotificationTypeAlert)];
        }
        
    }
    @catch (NSException *exception) {
        NSLog(@"Exception :%@",exception.debugDescription);
    }
    
}


//set the userInfo Dictionary using @"uid" key

-(void)setLocalnotfication:(NSDictionary *)userInfo title:(NSString *)title date:(NSDate *)fireDate Interactive : (BOOL)flag {
    
   
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = fireDate;
    notification.alertBody = title;
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    if(flag) notification.category = NCI;
    if([userInfo isKindOfClass:[NSDictionary class]]) 
    notification.userInfo = userInfo;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    
}

// cancel Particular notification use userInfo dictionary to match the notification to delete
-(void)cancelLocalnotifcation :(NSString *)identificationString {
    
    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:identificationString])         {             //Cancelling local notification             [app cancelLocalNotification:oneEvent];             break;         }     } } // cancel all local notification notification -(void) cancelAllnotification {     [[UIApplication sharedApplication] cancelAllLocalNotifications]; } // Interactive Local Notification create // its supported in above iOS 8 version - (void)setRegisterInteractiveLocalnotification :(NSArray*)getIdentificatioArray titleArray : (NSArray *)titleArray {           UIUserNotificationSettings *settings;          if([getIdentificatioArray count]>0) {
        
        NSMutableArray *setAction = [[NSMutableArray alloc]init];
        // 1 create dynamic action
        [getIdentificatioArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UIMutableUserNotificationAction *action;
            action = [[UIMutableUserNotificationAction alloc] init];
            [action setActivationMode:UIUserNotificationActivationModeBackground];
            [action setTitle:[titleArray objectAtIndex:idx]];
            [action setIdentifier:[getIdentificatioArray objectAtIndex:idx]];
            [action setDestructive:NO];
            [action setAuthenticationRequired:NO];
            [setAction addObject:action];  // 2. add each and every action in the array
            
        }];
        
        // 3 action array set to the category
        //try it to make a dynamic category
        
        UIMutableUserNotificationCategory *actionCategory;
        actionCategory = [[UIMutableUserNotificationCategory alloc] init];
        [actionCategory setIdentifier:NCI];
        [actionCategory setActions:setAction
                    forContext:UIUserNotificationActionContextDefault];
    
    
        // 4 set category to the settings with notification type
        NSSet *categories = [NSSet setWithObject:actionCategory];
        UIUserNotificationType types = (UIUserNotificationTypeAlert|
                                    UIUserNotificationTypeSound|
                                    UIUserNotificationTypeBadge);
    
   
        settings = [UIUserNotificationSettings settingsForTypes:types
                                                 categories:categories];
    }
    else {
    // without interactive local notification
        settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    // 5 register the local notification
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

}



-(void) handleLocalnotificationActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler  {
    
    if ([identifier isEqualToString:UID_1]) {
        
        NSLog(@"You chose action 1.");  //confirm
    }
    else if ([identifier isEqualToString:UID_2]) {
        
        NSDateFormatter *dtf = [[NSDateFormatter alloc] init];
        [dtf setDateFormat:@"yyyy-MM-dd"];
        
        NSDate *fireDate =[[NSDate date] dateByAddingTimeInterval:10];
        
        NSString *due = [NSString stringWithFormat:@"To renew your car insurance. Your due date on %@.",[dtf stringFromDate:fireDate]];
        NSString *endDateFormating = [NSString stringWithFormat:@"%@ 08:00:00",[dtf stringFromDate:fireDate]];
        NSDateFormatter *dateFormate = [[NSDateFormatter alloc] init];
        [dateFormate setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
        fireDate = [dateFormate dateFromString:endDateFormating];
        
        [self setLocalnotfication:userInfo title:due date:fireDate Interactive:YES];
        NSLog(@"You chose action 2."); //Again
    }
    else {
        
        NSLog(@"normal notification");
    }
    if (completionHandler) {
        
        completionHandler();
    }
}


@end


Access the file in viewcontroller

#import"Notification.h"
-(void)viewDidLoad {
NSString *due = [NSString stringWithFormat:@"To renew your car insurance. 
Your due date on %@.",endDateString];
NSString *endDateFormating = [NSString stringWithFormat:@"%@ 08:00:00",endDateString];

NSDateFormatter *dateFormate = [[NSDateFormatter alloc] init];
[dateFormate setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; // set Date format
NSDate *fireDate = [dateFormate dateFromString:endDateFormating];
 //fireDate =[fireDate dateByAddingTimeInterval:setInt*24*60*60];   
// setInt is the integer variable which using to pass the days you need
  fireDate =[[NSDate date] dateByAddingTimeInterval:10]; 
 // after 10 sec local notification will fire
[[Notification instance]setLocalnotfication:insuraceDetails 
title:due date:fireDate Interactive:YES];

}

In appdelegate File need to add the below code the handle the received notification

    - (void)application:(UIApplication *)application 
handleActionWithIdentifier:(nullable NSString *)identifier 
forLocalNotification:(nonnull UILocalNotification *)notification
 completionHandler:(nonnull void (^)())completionHandler {
   
    // handling local and interactive notifcation 
    [[Notification instance]handleLocalnotificationActionWithIdentifier:identifier 
forRemoteNotification:notification.userInfo
completionHandler:completionHandler];
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s