actions not showing in local notification - ios

I am trying to generate a local notification with 2 actions. However, even though the notifications are popping up. I am not able to see the actions.
Is this because of something new in iOS 10
my viewcontroller,h has code:
-(void)createNotifications: (int)seconds{
UILocalNotification *local = [[UILocalNotification alloc]init];
local.fireDate = [[NSDate date]dateByAddingTimeInterval:seconds];
local.timeZone = nil;
local.alertBody = #"Alert body";
local.alertTitle = #"Alert Title";
local.alertAction = #"Okay";
local.soundName = UILocalNotificationDefaultSoundName;
local.applicationIconBadgeNumber = 4127;
local.category = #"MAIN_CATEGORY";
[[UIApplication sharedApplication] scheduleLocalNotification:local];
}
-(void)requestPermissionToNotify{
UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc]init];
action.identifier = #"FLOAT_ACTION";
action.title = #"float";
action.activationMode = UIUserNotificationActivationModeBackground;
action.destructive = YES;
action.authenticationRequired = NO;
UIMutableUserNotificationAction *stingAction = [[UIMutableUserNotificationAction alloc]init];
stingAction.identifier = #"STING_ACTION";
stingAction.title = #"sting";
stingAction.activationMode = UIUserNotificationActivationModeForeground;
stingAction.destructive = NO;
stingAction.authenticationRequired = NO;
UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc]init];
category.identifier = #"MAIN_CATEGORY";
NSSet *categories = [NSSet setWithObjects:category, nil];
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[category setActions:#[action,stingAction] forContext:UIUserNotificationActionContextDefault];
}
my appdelegate.m has callback handlers:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
application.applicationIconBadgeNumber = 0;
UILocalNotification *localnotif = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
if(localnotif){
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Received while launch" message:localnotif.alertBody preferredStyle:UIAlertViewStyleDefault];
UIAlertAction *aa = [UIAlertAction actionWithTitle:#"okay" style:UIAlertViewStyleDefault handler:nil];
[alert addAction:aa];
dispatch_async(dispatch_get_main_queue(), ^{
[application.keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
});
}
return YES;
}
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
application.applicationIconBadgeNumber = 0;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Received while running" message:notification.alertBody preferredStyle:UIAlertViewStyleDefault];
UIAlertAction *aa = [UIAlertAction actionWithTitle:#"okay" style:UIAlertViewStyleDefault handler:nil];
[alert addAction:aa];
dispatch_async(dispatch_get_main_queue(), ^{
[application.keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
});
}
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Received while action" message:identifier preferredStyle:UIAlertViewStyleDefault];
UIAlertAction *aa = [UIAlertAction actionWithTitle:#"okay" style:UIAlertViewStyleDefault handler:nil];
[alert addAction:aa];
dispatch_async(dispatch_get_main_queue(), ^{
[application.keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
});
completionHandler();
}

You might be going in the wrong direction for adding action in the local notification. You need to add category along with action identifier while asking for permission. Please check below code for adding action and handling action tap in notification
// Ask for permission to allow Notification
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")){
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNNotificationAction *action = [UNNotificationAction actionWithIdentifier:#"ActionIdentifier" title:#"NewAction" options:UNNotificationActionOptionNone];
NSArray *notificationActions = #[action];
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:#"Notification" actions:notificationActions intentIdentifiers:#[] options:UNNotificationCategoryOptionCustomDismissAction];
NSSet *categories = [NSSet setWithObject:category];
[center setNotificationCategories:categories];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
if(!granted) {
}
}];
}
else {
UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc] init];
action.identifier = #"ActionIdentifier";
action.title = #"NewAction";
action.activationMode = UIUserNotificationActivationModeBackground;
action.destructive = NO;
action.authenticationRequired = NO;
UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc] init];
category.identifier = #"ActionIdentifier";
[category setActions:#[action] forContext:UIUserNotificationActionContextDefault];
[category setActions:#[action] forContext:UIUserNotificationActionContextMinimal];
NSSet *categories = [NSSet setWithObjects:category, nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:categories]];
}
// Handle Notification for iOS 10
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
// Handle Notification here
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
NSString *actionIdentifier = response.actionIdentifier;
BOOL newActionTapped = [actionIdentifier isEqualToString:#"NewAction"];
if(snooze) {
// Handle NewAction action button here
}
else {
// Handle Notification here
}
completionHandler();
}
// Handle Notification for iOS 9 or lower
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
// Handle Notification here
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler {
// This method will be called when user tap on Action
// Handle NewAction action button here
if (completionHandler) {
completionHandler();
}
}

Related

How to implement interactive remote notifications in iOS Objective-c

I am new in Objective-c. I want to create a interactive remote notification which have two action, one is call 'OK' and another is called 'VIEW'. When user receive notification through APNS that time if user click 'OK' the notification have to be dismiss and if user click 'VIEW' that time open a particular page of my app. That's it.
I have go through many web documents and grab some concept of notification payload. But I am not able to implement this step wise. Can any one assist me, how can I implement this functionality. And please anyone don't mark as a duplicate question. Thanks
Note: I have use my own constants here for category like KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID use your at that place
Register for push
- (void) registerPushNotification {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:type categories:[NSSet setWithObjects:[self createActionNotificationsSettingForApproveBID],[self createActionNotificationsSettingForCancelingRequest ], nil]];
[[UIApplication sharedApplication] registerUserNotificationSettings:setting];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
- (UIMutableUserNotificationCategory *) createActionNotificationsSettingForApproveBID {
UIMutableUserNotificationAction *actionApproveBID = [[UIMutableUserNotificationAction alloc] init];
[actionApproveBID setIdentifier:KNotificatoin_IDENTIFER_ACTION_APPROVEBID];
actionApproveBID.activationMode = UIUserNotificationActivationModeForeground;
actionApproveBID.title = #"Approve";
actionApproveBID.authenticationRequired = true;
[actionApproveBID setDestructive: false];
UIMutableUserNotificationAction *actionCancelDialog = [[UIMutableUserNotificationAction alloc] init];
[actionCancelDialog setIdentifier:KNotificatoin_IDENTIFER_ACTION_DETAILS];
actionCancelDialog.activationMode = UIUserNotificationActivationModeForeground;
actionCancelDialog.title = #"Details";
actionCancelDialog.authenticationRequired = true;
[actionCancelDialog setDestructive: false];
UIMutableUserNotificationCategory *cateogoryApproveBID = [[UIMutableUserNotificationCategory alloc] init];
cateogoryApproveBID.identifier = KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID;
[cateogoryApproveBID setActions:#[actionApproveBID,actionCancelDialog] forContext:UIUserNotificationActionContextDefault];
[cateogoryApproveBID setActions:#[actionApproveBID,actionCancelDialog] forContext:UIUserNotificationActionContextMinimal];
return cateogoryApproveBID;
}
- (UIMutableUserNotificationCategory *) createActionNotificationsSettingForCancelingRequest {
UIMutableUserNotificationAction *actionGetMoreBids = [[UIMutableUserNotificationAction alloc] init];
[actionGetMoreBids setIdentifier:KNotificatoin_IDENTIFER_ACTION_APPROVEBID];
actionGetMoreBids.activationMode = UIUserNotificationActivationModeForeground;
actionGetMoreBids.title = #"Get more bids";
actionGetMoreBids.authenticationRequired = true;
[actionGetMoreBids setDestructive: false];
UIMutableUserNotificationAction *actionEditRequest = [[UIMutableUserNotificationAction alloc] init];
[actionEditRequest setIdentifier:KNotificatoin_IDENTIFER_ACTION_EDIT_REQUEST];
actionEditRequest.activationMode = UIUserNotificationActivationModeForeground;
actionEditRequest.title = #"Edit request";
actionEditRequest.authenticationRequired = true;
[actionEditRequest setDestructive: false];
UIMutableUserNotificationCategory *categoryCancelRequest = [[UIMutableUserNotificationCategory alloc] init];
categoryCancelRequest.identifier = KNotificatoin_IDENTIFER_ACTION_MORE_BIDS;
[categoryCancelRequest setActions:#[actionGetMoreBids,actionEditRequest] forContext:UIUserNotificationActionContextDefault];
[categoryCancelRequest setActions:#[actionGetMoreBids,actionEditRequest] forContext:UIUserNotificationActionContextMinimal];
return categoryCancelRequest;
}
How you will handle actions ?
- (void) application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
NSLog(#" APPLICATION STATUS %ld",(long)[UIApplication sharedApplication].applicationState);
if ([[[userInfo objectForKey:#"aps"] objectForKey:kCategory] isEqualToString:KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID]){
if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_APPROVEBID]) {
NSMutableDictionary *dictData = [NSMutableDictionary dictionaryWithDictionary:userInfo];
[dictData setObject:#17 forKey:kType];
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
[self saveDictionaryForPushActiveState:dictData];
} else {
[self navigatateAsPerPush:dictData allowInActiveState:NO];
}
}
else if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_DETAILS]) {
NSLog(#"You chose action 2.");
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
[self saveDictionaryForPushActiveState:userInfo];
} else {
[self navigatateAsPerPush:userInfo allowInActiveState:NO];
}
}
} else if ([[[userInfo objectForKey:#"aps"] objectForKey:kCategory] isEqualToString:KNotificatoin_IDENTIFIER_NOTIFICATION_REQUEST]){
NSMutableDictionary *dictData = [NSMutableDictionary dictionaryWithDictionary:userInfo];
if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_EDIT_REQUEST]) {
NSLog(#"You chose action 1.");
[dictData setObject:#16 forKey:kType];
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
[self saveDictionaryForPushActiveState:dictData];
} else {
[self navigatateAsPerPush:dictData allowInActiveState:NO];
}
}
else if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_MORE_BIDS]) {
NSLog(#"You chose action 2.");
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
[self saveDictionaryForPushActiveState:dictData];
} else {
[self navigatateAsPerPush:dictData allowInActiveState:NO];
}
}
}
if (completionHandler) {
completionHandler();
}
}
Hope it is helpful to you
With the iOS 12 SDK, your app take advantage of Interactive Controls in Notifications
Notification content app extensions now support user interactivity in custom views. If the content of your app’s notifications needs to prompt user interaction, add controls like buttons and switches.
To enable user interactions:
Open your Notification Content Extension’s info.plist file.
Add the UNNotificationExtensionUserInteractionEnabled key to your extension attributes. Give it a Boolean value, set to YES.
Here is reference like to know more
https://developer.apple.com/documentation/usernotificationsui/customizing_the_appearance_of_notifications
https://developer.apple.com/documentation/usernotificationsui/customizing_the_appearance_of_notifications
https://developer.apple.com/documentation/usernotificationsui

Not Receiving Push Notification in IOS 10.3.1 and Receiving twice in ios 9

I am using Version 8.2.1. The Issue is I am not getting notifications in IOS 10.3.1 but I am getting notifications in IOS 9(but twice).
Here is my code which I tried :
//In **didFinishLaunchingWithOptions**
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
if( SYSTEM_VERSION_LESS_THAN( #"10.0" ) )
{
if ([application respondsToSelector:#selector(isRegisteredForRemoteNotifications)])
{
// iOS 8 Notifications
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
}
}
else
{
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) compl
etionHandler:^(BOOL granted, NSError * _Nullable error)
{
if( !error )
{
[[UIApplication sharedApplication] registerForRemoteNotifications]; // required to get the app to do anything at all about push notifications
NSLog( #"Push registration success." );
}
else
{
NSLog( #"Push registration FAILED" );
NSLog( #"ERROR: %# - %#", error.localizedFailureReason, error.localizedDescription );
NSLog( #"SUGGESTIONS: %# - %#", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );
}
}];
}
if([self pushNotificationOnOrOff]) {
NSLog(#"Push Notification is ON!");
} else {
NSLog(#"Push Notification is OFF.");
}
if (launchOptions != nil)
{
NSDictionary* dictionary1 = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary1 != nil)
{
//RemoteNotification Payload
NSLog(#"Launched from push notification: %#", dictionary1);
Globals.instance.isNotification = TRUE;
NSString* iUUID = [[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey] objectForKey:#"UUID"];
[self.window makeKeyAndVisible];
NSDictionary* dictData = [Database getDataForUUID:iUUID];
if (dictData){
//Show dictData
}
}
}
**// Push Notification Receiving Methods**
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
NSString* deviceTokenStr = [NSString stringWithFormat:#"%#", deviceToken];
deviceTokenStr = [deviceTokenStr substringWithRange:NSMakeRange(1, deviceTokenStr.length-2)];
if (!Globals.instance.deviceToken) {
Globals.instance.deviceToken = deviceTokenStr;
}
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
NSLog(#"Failed to get token, error: %#", error);
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)notification {
NSDictionary* data = [self checkForData:notification];
if (data){
if (application.applicationState == UIApplicationStateActive) [self activeAlertForData: data];
else [self displayData: data];
}
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
NSLog(#"Userinfo %#",notification.request.content.userInfo);
completionHandler(UNNotificationPresentationOptionAlert);
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
NSLog(#"Userinfo %#",response.notification.request.content.userInfo);
}
-(BOOL)pushNotificationOnOrOff
{
BOOL pushEnabled=NO;
if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
pushEnabled=YES;
} else {
pushEnabled=NO;
}
return pushEnabled;
}
- (NSDictionary*)checkForData:(NSDictionary*)notification {
NSString* iUUID = [notification objectForKey:#"UUID"];
NSDictionary* dict = [Database getUUID:iUUID];
NSString* alertData = [notification objectForKey:#"alert"];
return dict;
}
- (void)activeAlertForData:(Inc*)inc {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#"New Post”
message:inc.description
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
}];
UIAlertAction* noButton = [UIAlertAction
actionWithTitle:#“Open”
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
// Jump to Post.
}];
[alert addAction:yesButton];
[alert addAction:noButton];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
});
}
Please guide me to resolve this issue.
Thanks in Advance.

How to show a local notification on iOS 7-10 when receives a notification?

My app is receiving notifications from Firebase. When the notification is received, the app decides if it must to show a local notification. How can I show it?. I've tried this code, but doesn't appears any notification:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Register for remote notifications
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
// iOS 7.1 or earlier. Disable the deprecation warnings.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
} else {
// iOS 8 or later
// [START register_for_notifications]
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
#pragma unused(granted)
#pragma unused(error)
}
];
// For iOS 10 display notification (sent via APNS)
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
// For iOS 10 data message (sent via FCM)
[[FIRMessaging messaging] setRemoteMessageDelegate:self];
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
// [END register_for_notifications]
}
// [START configure_firebase]
[FIRApp configure];
// [END configure_firebase]
// Add observer for InstanceID token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
return YES;
}
-(void)dispathNotification:(UIApplication *)application userInfo:(NSDictionary *)userInfo {
NSLog(#"Received notification");
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = #"new notification";
content.body = #"show content";
content.sound = [UNNotificationSound defaultSound];
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:false];
NSString *identifier = [NSString stringWithFormat:#"%f", [[NSDate date] timeIntervalSince1970]];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:nil];
}
}];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[self dispathNotification:application userInfo:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[self dispathNotification:application userInfo:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
NSDictionary *userInfo = [remoteMessage appData];
[self dispathNotification:[UIApplication sharedApplication] userInfo:userInfo];
}
I found it!
When put this code, shows the notification:
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}
You should implement 2 different methods to handle local or remote notification. Look at the below.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
UIApplicationState state = [application applicationState];
if(state == UIApplicationStateActive){
NSString *message = #"";
if([message isEqualToString:#""] || message == nil)
message = #"local notify";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"local message"
message:message
delegate:self cancelButtonTitle:[[ContentKeeper getKeeper] getResourceForKey:#"OKButtonText"].Value
otherButtonTitles:nil];
[alert show];
}
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIApplicationState state = [application applicationState];
if (true) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Reminder"
message:notification.alertBody
delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}

How can I show a custom Local notification View or an Custom Alert view when app is in Background?

Actually I want to show a local notification in my app. But i want to show this notification with some custom design like ok and cancel button on it.And on the click of Ok and Cancel i want to perform some actions.Please suggest something.
Thanks In advance.
i am impliment this code for custom local notification may be helping you
where Accept is identifier where you get in delegates of local notification in appDelegate.m
NSString *idetnt = #"Accept";
NSString *idetnt1 = #"Reject";
NSString *idetnt2 = #"Local Notification";
UIMutableUserNotificationAction *notificationAction1 = [[UIMutableUserNotificationAction alloc] init];
notificationAction1.identifier = idetnt;
notificationAction1.title = #"Snooze";
notificationAction1.activationMode = UIUserNotificationActivationModeBackground;
notificationAction1.destructive = NO;
notificationAction1.authenticationRequired = NO;
UIMutableUserNotificationAction *notificationAction2 = [[UIMutableUserNotificationAction alloc] init];
notificationAction2.identifier = idetnt1;
notificationAction2.title = #"Call";
notificationAction2.activationMode = UIUserNotificationActivationModeBackground;
notificationAction2.destructive = YES;
notificationAction2.authenticationRequired = YES;
UIMutableUserNotificationAction *notificationAction3 = [[UIMutableUserNotificationAction alloc] init];
notificationAction3.identifier = #"Reply";
notificationAction3.title = #"Reply";
notificationAction3.activationMode = UIUserNotificationActivationModeForeground;
notificationAction3.destructive = NO;
notificationAction3.authenticationRequired = YES;
UIMutableUserNotificationCategory *notificationCategory = [[UIMutableUserNotificationCategory alloc] init];
notificationCategory.identifier = #"Email";
[notificationCategory setActions:#[notificationAction1,notificationAction2,notificationAction3] forContext:UIUserNotificationActionContextDefault];
[notificationCategory setActions:#[notificationAction1,notificationAction2] forContext:UIUserNotificationActionContextMinimal];
NSSet *categories = [NSSet setWithObjects:notificationCategory, nil];
UIUserNotificationType notificationType = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:notificationType categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:600];
localNotification.alertBody = idetnt2;
localNotification.category = #"Email";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
when ur app in background then this methods call
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler
{
if ([identifier isEqualToString:#"Accept"])
{
}
else if ([identifier isEqualToString:#"Reject"])
{
}
else if ([identifier isEqualToString:#"Reply"])
{
}
if(completionHandler != nil)
completionHandler();
}
when ur app in foreground then this methods call
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)localNotification
{
}
Go to capability option and click on remote notification
You can't add full customisation, but your notifications can set the category property to specify which notification settings should be used and those notification settings can specify which buttons to show and what those buttons to when the user selects them.

iOS Custom Action When Opening Notification

I know that I can set actions for an iOS notification like:
UIMutableUserNotificationAction *acceptAction =
[[UIMutableUserNotificationAction alloc] init];
acceptAction.identifier = #"THANKS_IDENTIFIER";
acceptAction.title = #"View News Page";
// Given seconds, not minutes, to run in the background
acceptAction.activationMode = UIUserNotificationActivationModeBackground;
acceptAction.destructive = NO;
acceptAction.authenticationRequired = NO;
UIMutableUserNotificationCategory *inviteCategory =
[[UIMutableUserNotificationCategory alloc] init];
inviteCategory.identifier = #"TAGGED_CATEGORY";
[inviteCategory setActions:#[acceptAction]
forContext:UIUserNotificationActionContextDefault];
NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes
categories:categories];
[[UIApplication sharedApplication]
registerUserNotificationSettings:settings];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
and include in the payload of the aps a category matching what is listed here, and when the app receives a notification of said category, it will add the action to it, and when that action button is pressed, perform the action here:
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)notification
completionHandler:(void (^)())completionHandler {
if ([identifier isEqualToString:#"THANKS_IDENTIFIER"]) {
[self handleAcceptActionWithNotification:notification];
}
// Must be called when finished
completionHandler();
}
-(void) handleAcceptActionWithNotification:(NSDictionary *)notification {
UIAlertView *test = [[UIAlertView alloc] initWithTitle:#"YAY" message:#"Success" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[test show];
[self.tabBarController setSelectedIndex:1];
[self performSelector:#selector(launchNews) withObject:nil afterDelay:1.0];
}
-(void)launchNews {
NewsViewController *dvController8 = [[NewsViewController alloc] initWithNibName:#"NewsViewController" bundle:[NSBundle mainBundle]];
[self.tabBarController.navigationController pushViewController:dvController8 animated:YES];
[dvController8 release];
}
However, is there a way that when a push notification of a certain category is received it performs a custom action, without the need of adding in an action button to the notification?
Here is my Payload, using cloudCode:
Parse.Cloud.define("newNews", function(request, response) {
var theTitle = request.params.articleTitle;
var pushQuery = new Parse.Query(Parse.Installation);
Parse.Push.send({
where: pushQuery,
data: {
alert: "A new article, \"" + theTitle + "\" was just posted. Open app to view.",
category : "TAGGED_CATEGORY",
sound: "default.caf"
}
}).then(function() {
response.success("Push was sent successfully.")
}, function(error) {
response.error("Push failed to send with error: " + error.message);
});
});
UPDATED CODE:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[PFPush handlePush:userInfo];
if (application.applicationState == UIApplicationStateInactive) {
[self handleRemoteNotificationWithPayload:userInfo];
}
}
-(void)handleRemoteNotificationWithPayload:(NSDictionary *)payload {
NSString *thePayload = [payload valueForKey:#"category"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Hi" message:thePayload delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alertView show];
if ([thePayload isEqualToString:#"TAGGED_CATEGORY"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Hi" message:#"Received with category" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alertView show];
[self.tabBarController setSelectedIndex:4];
}
}

Resources