Push notification issue in ios - 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.

Related

How to Turn On Off Notification from application reflect into iPhone settings

How to turn On Off Notificiation form app with using component UISwitch.
From setting if user turn On/Off Notification of any specific application UISwitch is turn On/Off using
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationEnteredForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
- (void)applicationEnteredForeground:(NSNotification *)notification {
NSLog(#"Application Entered Foreground");
[self notificationEnableDisable];
}
-(void)notificationEnableDisable{
NSString *iOSversion = [[UIDevice currentDevice] systemVersion];
NSString *prefix = [[iOSversion componentsSeparatedByString:#"."] firstObject];
float versionVal = [prefix floatValue];
if (versionVal >= 8)
{
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone)
{
NSLog(#" Notification ON");
[self.switch_DailyNotification setOn:YES];
}
else
{
[self.switch_DailyNotification setOn:NO];
NSLog(#" Notification OFF");
}
}
else
{
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types != UIRemoteNotificationTypeNone)
{
NSLog(#"Notification ON");
[self.switch_DailyNotification setOn:YES];
}
else
{
[self.switch_DailyNotification setOn:NO];
NSLog(#" Notification OFF");
}
}
}
This above code work fine when user turn On/Off Notification from IPhone setting.
How to implement from application to turn On/Off Notification which is in IPhone setting?
Note: This is for LocalNotification not for PushNotification!
You can't do that due to apple restrictions it doesn't matter if its local or push notification:
https://stackoverflow.com/a/10510610/8873550

Get Local notification text on tap when App is minimize 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

Issue with implementing badges in ios

I am working in ios app in phonegap with pushnotification.i have added the below code in Appdelegate+notification.m
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
PushPlugin *pushHandler = [self getCommandInstance:#"PushPlugin"];
[pushHandler didFailToRegisterForRemoteNotificationsWithError:error];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"didReceiveNotification");
// Get application state for iOS4.x+ devices, otherwise assume active
UIApplicationState appState = UIApplicationStateActive;
if ([application respondsToSelector:#selector(applicationState)]) {
appState = application.applicationState;
}
if (appState == UIApplicationStateActive) {
PushPlugin *pushHandler = [self getCommandInstance:#"PushPlugin"];
pushHandler.notificationMessage = userInfo;
pushHandler.isInline = YES;
[pushHandler notificationReceived];
} else {
//save it for later
self.launchNotification = userInfo;
}
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + [[[userInfo objectForKey:#"aps"] objectForKey: #"badge"] intValue];
}
I am using pushNotification.java file for sending push message to our application in that i have mentioned payload.addBadge(1);
So in my app badge gets update onclick of notification Please suggest me how to do it while receiving notification

Notification Badge In UITableView Cell

Currently my app receives notifications about updates to an RSS feed. If the user opens the app from the notification, it opens to the correct view controller. If the user does not acknowledge the notification and opens the app from the app icon, when the user opens the menu within the app, the table view cell for that rss feed has a badge icon with the applicationIconBadgeNumber. Once that row is selected, the badge on that cell goes away and the applicationIconBadgeNumber is reset. My question is about wanting to send notifications about other info within the app such as member benefits. How can I differentiate which row in the table view gets the badge? Say the user gets a notification about a member benefit. I would want the badge to appear in the member benefits row of the table view, but if there is a notification from the RSS feed, badge the appropriate row.
Here is how I'm currently adding the badge for the RSS feed row.
in cellForRowAtIndexPath:
if (!(indexPath.row == 0))
{
cell.accessoryView = nil;
}
badgeNumber = [NSString stringWithFormat:#"%ld", (long)[[UIApplication sharedApplication]applicationIconBadgeNumber]];
actionAlertBadge = [JSCustomBadge customBadgeWithString:badgeNumber withStringColor:[UIColor whiteColor] withInsetColor:[UIColor redColor] withBadgeFrame:NO withBadgeFrameColor:[UIColor redColor] withScale:1.0 withShining:NO withShadow:NO];
actionAlertBadge.frame = CGRectMake(83, 6, 30, 30);
if ([badgeNumber isEqualToString:#"0"])
{
actionAlertBadge.hidden = YES;
}
if (actionAlertBadge.hidden == NO)
{
if (indexPath.section == 0)
{
if (indexPath.row == 0)
{
cell.accessoryView = actionAlertBadge;
}
}
}
in didSelectRowAtIndexPath:
if (indexPath.row == 0)
{
ActionAlertsViewController *actionAlerts = [[ActionAlertsViewController alloc]initWithStyle:UITableViewStylePlain];
WebViewController *wvc = [[WebViewController alloc]init];
[actionAlerts setWebViewController:wvc];
[[UAPush shared] resetBadge];
actionAlertBadge.hidden = YES;
[tableView reloadData];
navController = [[KFBNavControllerViewController alloc]initWithRootViewController:actionAlerts];
[UIView transitionWithView:appDelegate.window
duration:0.5
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
appDelegate.window.rootViewController = navController;
}
completion:nil];
}
EDIT: Here is how I'm trying to accomplish this but it is not working because my notificationType string in my table view is NULL.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
UA_LINFO(#"Received remote notification: %#", userInfo);
// Send the alert to UA so that it can be handled and tracked as a direct response. This call
// is required.
[[UAPush shared]appReceivedRemoteNotification:userInfo applicationState:application.applicationState];
// Optionally provide a delegate that will be used to handle notifications received while the app is running
// [UAPush shared].delegate = your custom push delegate class conforming to the UAPushNotificationDelegate protocol
// Reset the badge after a push received (optional)
[[UAPush shared] resetBadge];
NSDictionary *apsInfo = [userInfo valueForKey:#"aps"];
NSString *alertMsg = #"";
if ([apsInfo valueForKey:#"alert"] != NULL) {
alertMsg = [apsInfo valueForKey:#"alert"];
if ([alertMsg containsString:#"ACTION ALERT"]) {
notificationType = #"action alert";
}
else if ([alertMsg containsString:#"MEMBER BENEFIT"]) {
notificationType = #"member benefit";
}
}
}
cellForRowAtIndexPath:
KFBAppDelegate *appDelegate = (KFBAppDelegate *)[[UIApplication sharedApplication]delegate];
NSString *notificationType = appDelegate.notificationType;
// NSLog(#"notificationType menu table: %#", notificationType);
badgeNumber = [NSString stringWithFormat:#"%ld", (long)[[UIApplication sharedApplication]applicationIconBadgeNumber]];
actionAlertBadge = [JSCustomBadge customBadgeWithString:badgeNumber withStringColor:[UIColor whiteColor] withInsetColor:[UIColor redColor] withBadgeFrame:NO withBadgeFrameColor:[UIColor redColor] withScale:1.0 withShining:NO withShadow:NO];
actionAlertBadge.frame = CGRectMake(83, 6, 30, 30);
if ([badgeNumber isEqualToString:#"0"]) {
actionAlertBadge.hidden = YES;
}
if (actionAlertBadge.hidden == NO) {
if ([notificationType isEqualToString:#"action alert"]) {
if (indexPath.section == 0) {
if (indexPath.row == 0) {
cell.accessoryView = actionAlertBadge;
}
}
}
else if ([notificationType isEqualToString:#"member benefit"]) {
if (indexPath.section == 0) {
if (indexPath.row == 5) {
cell.accessoryView = actionAlertBadge;
}
}
}
}
In your AppDelegate, first make a property:
#property (nonatomic, copy) NSString *notificationType;
Then, in your
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
use:
self.notificationType = #"action alert";
self.notificationType = #"member benefit";
and in your CellForRowAtIndexPath:
if (actionAlertBadge.hidden == NO) {
if ([appDelegate.notificationType isEqualToString:#"action alert"]) {
....
}
else if ([appDelegate.notificationType isEqualToString:#"member benefit"]) {
....
}
On a side note, I would suggest trying to refrain from string comparisions and use something like enums.
First, while sending notification, you should add a field of type in the notification. You will get json dictionary like this
{"aps":{"alert":{"type":"rss","text":"Hello, world!"},"sound":"default","badge":3}}
Get the type value in function (if the app is running)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)dict {
// get the type information out of the dictionary
// now you can perform depending on this type.
}
If the app is not running,then according to apple's documentation
"If the app is not running when a push notification arrives, the method launches the app and provides the appropriate information in the launch options dictionary. The app does not call this method to handle that push notification. Instead, your implementation of the application:willFinishLaunchingWithOptions: or application:didFinishLaunchingWithOptions: method needs to get the push notification payload data and respond appropriately."
Get your dictionary in application:didFinishLaunchingWithOptions: method.

Handling Apple Push Notification Service

I'm using apple push notification service in my project.
Please follow the 2 ways of opening the app and handling this push notifications. In the second scenario I do not know how to handle it. Do you know how?
The push notification arrived to my device,
Scenario 1:
I clicked on the push notification.
The - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo function AppDelegate.m file catches this function.
Scenario 2:
I normally opened the device (by clicking on the app)
How can I handle the push notification?
The other answers show how to get the notification data when the user taps the notification.
The difference between the two nethods shown is that one is called when app is already running, either in foreground or background, while the other is called when app is not running at all.
On your second case, when the user doesn't tap the notification, the notification data isn't passed to the app when you open it with the launch Icon.
First scenario:
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
NSLog (#"APNS: notification received: %#", userInfo);
NSString *message = nil;
id alert = [userInfo objectForKey:#"aps"];
if ([alert isKindOfClass:[NSString class]])
{
message = alert;
}
else if ([alert isKindOfClass:[NSDictionary class]])
{
message = [alert objectForKey:#"alert"];
}
if (message)
{
if (![message isEqualToString:#""])
{
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle: #"notification"
message: message
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
}
Second scenario:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog (#"LAUNCH OPTIONS: %#",launchOptions);
id remoteNotificationValue = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotificationValue)
{
NSString *message = nil;
id alert = [remoteNotificationValue objectForKey:#"aps"];
if ([alert isKindOfClass:[NSString class]])
{
message = alert;
}
else if ([alert isKindOfClass:[NSDictionary class]])
{
message = [alert objectForKey:#"alert"];
}
if (message)
{
if (![message isEqualToString:#""])
{
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle: #"notification"
message: message
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
}
....
Of course you might want to make a special method that handles notifications and is called from both scenarios (with NSDictionary * parameter) so your code would be more readable. Sometimes APNS notifications are useful also when app is running - empty notification (with no payload) might be used to trigger the data synchronization with server to avoid polling for example.
You can get the arrived notifications when the app starts with the following code (e.g: in application:didFinishLaunchingWithOptions):
NSDictionary *remoteNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
Here is a more thorough explanation: How to manage notification when users click on badge
You can handle that like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Checking if app was launched from the notification
if (launchOptions != nil) {
NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil){
// Read dictionary and do something since the app
// was launched from the notification.
}
}
Here is an example of what the dictionary object contains
NSString *message = #"";
NSString *badge = #"";
NSString *sound = #"";
if([dictionary objectForKey:#"alert"]) {
message = [dictionary objectForKey:#"alert"];
}
if([dictionary objectForKey:#"badge"]) {
badge = [dictionary objectForKey:#"badge"];
}
if([dictionary objectForKey:#"sound"]) {
sound = [dictionary objectForKey:#"sound"];
}
Hope it helps!

Resources