Get Local notification text on tap when App is minimize ios - ios

Example:-
I have generated 4 local notifications with 4 types in minimize State.
Type of notifications below.
Message
Friend Request
Video call
Audio call
notifications are shown in notification center.
Noow..I have clicked on 2nd notification,
How can i get which number of notification clicked?
How can i get 2nd notification body alert text(content)?
this mehod is not working for minimize state
like whatsApp.. I need to go on specific screen according to Notification type.
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type {
NSString *Notitype=#"";
if ([[payload.dictionaryPayload valueForKey:#"type"]isEqualToString:#"video"]) {
Notitype=#"video";
}
else if ([[payload.dictionaryPayload valueForKey:#"type"]isEqualToString:#"friendRequest"]) {
Notitype=#"friend Request";
}
else if([[payload.dictionaryPayload valueForKey:#"type"] isEqualToString:#"message"] )
{
Notitype=#"message";
}
else{
Notitype=#"audio";
}
I'm creating UILocalNotification like this :
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:Notitype];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[[UIApplication sharedApplication] setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];

For Set local notification as:
// Schedule the notification
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:Notitype];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
//Create user info for local notification.
NSDictionary* dict = #{#"Type": #"message", #"ID": #"set your unique ID", #"body": notification.alertBody,};
notification.userInfo = dict;
//You can Set Type as: message, friend Request, video call, Audio call.
[[UIApplication sharedApplication] setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
for get which type of local notifications is click than you can use didReceiveLocalNotification delegate.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
//[super application:application didReceiveLocalNotification:notification]; // In most case, you don't need this line
//Get notification type
NSString *notificationType = [notification.userInfo valueForKey:#"Type"];
//notificationType as: message, friend Request, video call, Audio call.
NSString *notificationBody = [notification.userInfo valueForKey:#"Notification_body"];
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
// Application in foreground when notification is delivered.
if ([notificationType isEqual:#"message"]) {
//Handle message
} else if ([notificationType isEqual:#"friend Request"]) {
//Handle friend Request
} else if ([notificationType isEqual:#"video call"]) {
//Handle video call
} else if ([notificationType isEqual:#"Audio call"]) {
//Handle Audio call
}
} else if (state == UIApplicationStateBackground) {
// Application was in the background when notification was delivered.
if ([notificationType isEqual:#"message"]) {
//Handle message
} else if ([notificationType isEqual:#"friend Request"]) {
//Handle friend Request
} else if ([notificationType isEqual:#"video call"]) {
//Handle video call
} else if ([notificationType isEqual:#"Audio call"]) {
//Handle Audio call
}
} else {
}
}
Update
Also check this same things in DidFinishLaunchingWithOptions, possible user don't react on notification, but tap on App icon to open app. So in case of video call or anything urgent then it must be handled through DidFinishLaunchingWithOptions

Related

Slient Push Notification not getting in iOS

I am trying lot but not succeed yet to get silent notification when app is killed state
Here code I am trying ..
APS data:
{
"aps": {
"content-available": 1,
"sound": ""
}
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSDictionary *userInfo1 = userInfo;
NSLog(#"userInfo: %#", userInfo1);
//self.textView.text = [userInfo description];
// We can determine whether an application is launched as a result of the user tapping the action
// button or whether the notification was delivered to the already-running application by examining
// the application state.
if (application.applicationState == UIApplicationStateActive)
{
//opened from a push notification when the app was on background
NSLog(#"userInfoUIApplicationStateactive->%#",[userInfo objectForKey:#"aps"]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Did receive a Remote Notification" message:[NSString stringWithFormat:#"Your App name received this notification while it was Running:\n%#",[[userInfo objectForKey:#"aps"] objectForKey:#"alert"]]delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else
{
// a push notification when the app is running. So that you can display an alert and push in any view
NSLog(#"userInfoUIApplicationStateBackground->%#",[userInfo objectForKey:#"aps"]);
[self scheduleAlarmForDate1:[NSDate date]alarmDict:userInfo];
}
}
In the payload’s aps dictionary must not contains the alert, sound, or badge keys.
{
"aps":{
"content-available" : 1
}
}
Please try this.
You should implement as in AppDelegate.m
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
NSDictionary *aps = [userInfo objectForKey:#"aps"];
NSLog(#"hello");
NSLog(#"userinfo---->>>>%#",userInfo);
[UIApplication sharedApplication].applicationIconBadgeNumber=[[aps objectForKey:#"badge"] integerValue];
[self application:application didReceiveRemoteNotification:userInfo];
}

iOS, force quit app first, after tapping the receiving notification banner, app launch failed

I use APNs to send the notifications to my app. But my app does not work well when I did the following steps:
steps
swipe the app to force quit (app is not running, not in background mode ..)
send the notification from APNs
got the notification on my iPhone and I tapped the notification banner
app seemed to try to launch(showed the launch image), but launched fail (crash?)
my app can receive notification foreground and background.
Tap the notification banner in background then it can bring app to foreground then go to the view I wrote, everything works fine.
Except force quit the APP
here is my code in AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
MFSideMenuContainerViewController *container = [MFSideMenuContainerViewController
containerWithCenterViewController:[self navigationController]
leftMenuViewController:leftMenuViewController
rightMenuViewController:rightMenuViewController];
self.window.rootViewController = container;
[self.window makeKeyAndVisible];
UIMutableUserNotificationAction *acceptAction =
[[UIMutableUserNotificationAction alloc] init];
// Define an ID string to be passed back to your app when you handle the action
acceptAction.identifier = #"MARK_AS_READ_IDENTIFIER";
// Localized string displayed in the action button
acceptAction.title = NSLocalizedString(#"Mark as Read", nil);
// If you need to show UI, choose foreground
acceptAction.activationMode = UIUserNotificationActivationModeBackground;
// Destructive actions display in red
acceptAction.destructive = NO;
// Set whether the action requires the user to authenticate
acceptAction.authenticationRequired = NO;
// First create the category
UIMutableUserNotificationCategory *inviteCategory =
[[UIMutableUserNotificationCategory alloc] init];
// Identifier to include in your push payload and local notification
inviteCategory.identifier = #"actionCategory";
// Add the actions to the category and set the action context
[inviteCategory setActions:#[acceptAction]
forContext:UIUserNotificationActionContextDefault];
// Set the actions to present in a minimal context
[inviteCategory setActions:#[acceptAction]
forContext:UIUserNotificationActionContextMinimal];
NSSet *categories = [NSSet setWithObject:inviteCategory];
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert) categories:categories]];
// for calling didReceiveRemoteNotification when app first launch
if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
[self application:application didReceiveRemoteNotification:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]];
}
return YES;
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
//register to receive notifications
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"Device token: %#",deviceToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Fail to get device token: %#", error);
}
// tap the backgraund banner button
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)newUserInfo completionHandler:(void (^)())completionHandler {
if ([identifier isEqualToString:#"MARK_AS_READ_IDENTIFIER"]) {
// when tapping the background banner's button will mark the notification status to read
[Functions updateComingNotificationToRead];
}
if (completionHandler) {
completionHandler();
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)newUserInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
//NSLog(#"Notification received: %# %#", newUserInfo,[newUserInfo objectForKey:#"aps"] );
userInfo = newUserInfo;
NSString *alertMessage = [[newUserInfo objectForKey:#"aps"] objectForKey:#"alert"];
UIApplicationState state = [application applicationState];
UIAlertView *alertView = nil;
// for background banner use
switch (state) {
case UIApplicationStateActive: // when app is alive, show alert to notify user
alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"SmartHome",nil) message:NSLocalizedString(alertMessage,nil) delegate:self cancelButtonTitle:NSLocalizedString(#"Close",nil) otherButtonTitles:NSLocalizedString(#"Open",nil),NSLocalizedString(#"Mark as Read",nil), nil];
[alertView show];
break;
case UIApplicationStateBackground: // app is in background mode
// user tap the banner or tap the mark as read button, code will go here
[Functions addNotificationDataInDatabase:[newUserInfo objectForKey:#"uniqueID"] type:[newUserInfo objectForKey:#"deviceType"] event:[newUserInfo objectForKey:#"event"] time:[newUserInfo objectForKey:#"time"] read:#"0" description:alertMessage];
break;
case UIApplicationStateInactive: // tapping the banner
//NSLog(#"UIApplicationStateInactive");
// go to notification view
// because will go to the notification view detail, set status to read
[self gotoNotificationView:userInfo]; //uniqueID
break;
default:
break;
}
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
handler(UIBackgroundFetchResultNoData);
// send post notification for updating the badge, will get the notification in foreground
[[NSNotificationCenter defaultCenter] postNotificationName:#"APNsNotification" object:self userInfo:nil];
}
Does anyone have this problem before? Did I miss something?
Please help me!!
u can put alert and check launchOptions
if (launchOptions) {
if ([launchOptions objectForKey:#"UIApplicationLaunchOptionsRemoteNotificationKey"]) {
[self application:self didReceiveRemoteNotification:[launchOptions objectForKey:#"UIApplicationLaunchOptionsRemoteNotificationKey"] fetchCompletionHandler:^(UIBackgroundFetchResult result) {
}];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)newUserInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
NSString *str = [[userInfo objectForKey:#"aps"] objectForKey:#"alert"];
}
}

iOS Local Notification - Action on Click

So I have managed to set up local notification in my app by doing so.
NSDate *notifTime = [[NSDate date] dateByAddingTimeInterval:time];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notif = [[UILocalNotification alloc] init];
if (notif) {
notif.fireDate = notifTime;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.repeatInterval = 0;
notif.alertTitle = title;
notif.alertBody = text;
if (sound == nil) {
NSLog(#"default sound");
}
else {
NSLog(#"other sound");
notif.soundName = sound;
};
[app scheduleLocalNotification:notif];
}
inside of a method that is called
- (void)createDateNotification:(NSString*) title alertText: (NSString*)text timeToWait: (NSTimeInterval)time soundToPlay: (NSString*)sound;
and when I call that method, The notification runs just like expected. My problem is that in my game I want it to be when the user clickes on the local notification that it will run a method which now just does so
-(void)rewardUser {
NSLog(#"User rewarded")
}
but sometimes it may run a different method and I don't know how do do it. Anything from swift to objective c will be appreciated. Much thanks!
Override - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification in your AppDelegate and do your thing.
I managed to solve it by doing this. When creating the alert, I set the action to a public string in my class which is called action and as #songchenwen mentioned, I overrided the didReceiveLocalNotification to check if the action is equal to a number of variables and if so run a method for each one.
I called the mothod like this setting a string for the action
[self createReminderNotification:#"Give50Coins" messageTitle:#"t" messageBody:#"gfdhgsh" timeToWait:2 soundToPlay:#"audio.wav"];
And in the method I initialised the notification setting all the details.
NSDate *notifTime = [[NSDate date] dateByAddingTimeInterval:time];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notif = [[UILocalNotification alloc] init];
action = actionAfterNotifiy;
if (notif) {
notif.fireDate = notifTime;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.repeatInterval = 0;
notif.alertTitle = title;
notif.alertBody = message;
if (sound == nil) {
NSLog(#"default sound");
}
else {
NSLog(#"other sound");
};
}
[app scheduleLocalNotification: notif];
and in the - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification
I did this,
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if ([action isEqualToString:#"Give50Coins"]) {
NSLog(#"wheyy");
}
else {
//random stuff here
}
}

Push notification issue in ios

Hi i am new for push notification and i am working on a project there push notification have been used ,
i understand all code but not [[userInfo objectForKey:#"payload"] objectForKey:#"userId"]] where it can store value in userinfo ??
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary*) userInfo {
**if ([self.profileManager.profile.userId isEqualToString:[[userInfo objectForKey:#"payload"] objectForKey:#"userId"]]**) {
if (application.applicationState == UIApplicationStateActive) {
UIRemoteNotificationType apnsType = [application enabledRemoteNotificationTypes];
if(apnsType != UIRemoteNotificationTypeNone) {
if((apnsType & UIRemoteNotificationTypeAlert) != 0) {
[self showNotificationAlert:userInfo];
}
if((apnsType & UIRemoteNotificationTypeBadge) != 0) {
NSString* badge = [userInfo valueForKey:#"badge"];
application.applicationIconBadgeNumber = [badge intValue];
}
}
} else {
NSString* event = [[userInfo objectForKey:#"payload"] objectForKey:#"event"];
if ([event isEqualToString:#"QUESTION_ANSWERED"]) {
[self presentYouAsked];
} else if ([event isEqualToString:#"QUESTION_ASKED"]) {
[self presentFriendsAsked];
}
}
}
}
The userInfo dictionary is part of the push notification data that was received. The line you refer to extracts another dictionary, associated with the key "payload" from the push notification dictionary and then looks for the value associated with the key "userid" in that dictionary.
At a guess that "if" statement it determining whether the push notification that was received applies to the current user on this device.

Local Notifications not working When enter applicationDidBecomeActive

I am using Repeat Local notofications to display alerts to the user. For this i used below code
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [[NSDate date] dateByAddingTimeInterval:60];
localNotification.alertBody = #"sss";
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
Using NSNotification Centre i will call the local notification every 60 seconds. It is working fine.
Also in Appdelegate i use the following code:-
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
NSLog(#"Received");
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"RestartProcess" object:self];
}
application.applicationIconBadgeNumber = 0;
}
Also
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (locationNotification) {
// Set icon badge number to zero
NSLog(#"Yes Notid=fications is predsent");
application.applicationIconBadgeNumber = 0;
}
return YES;
}
My problem is when local notification starts, i pressed on home button then waited to display. After the time period display a notification message.
When i clicked on app icon the process is stopped.After that Local notifications not working.But when i was clicked on Notification Message it will works right.How i can fix the problem.Can any one help me to do this. Thanks in advance..
didReceiveLocalNotification is only called when you hit on notification messaage. If you want to do it in applicationDidBecomeActive you have to do it manually.
You can check badge number count(if notification consists badge) like :
-(void) applicationDidBecomeActive:(UIApplication *)application
{
if(application.applicationIconBadgeNumber >= 1)
{
//Do you stuff here
application.applicationIconBadgeNumber = 0;
}
}
When you press home button:
UIApplicationState state = [application applicationState];
// at this time, state == UIApplicationStateInactive
When you click your application, i think you should implement in this method:
- (void)applicationDidBecomeActive:(UIApplication *)application- (void)applicationWillEnterForeground:(UIApplication *)application
{
UIApplicationState state = [application applicationState];
application.applicationIconBadgeNumber = 0;
//state at this time is UIApplicationStateInactive
if (state == UIApplicationStateInactive) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"RestartProcess" object:self];
}
}
Hope this helps you

Resources