Handling Apple Push Notification Service - ios

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!

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];
}

Watch OS 2.0 Actionable remote push notification is not working on Apple Watch

I am developing a project in watch 2.0 using wcsession.
My actionable notification has two type of button that is accept and reject.When i click on accept or reject ActionWithIdentifier then my delegate method is not call.
I am using this delegate in extensiondeleget.m
1.- (void)handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)remoteNotification
{
dicPlayLoad=remoteNotification;
self.strActionNotificationType = identifier;
[self notification:identifier withDic:remoteNotification];
}
2.- (void)handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)remoteNotification withResponseInfo:(NSDictionary *)responseInfo
{
dicPlayLoad=remoteNotification;
self.strActionNotificationType = identifier;
[self notification:identifier withDic:responseInfo];
}
-(void)notification:(NSString *)strIdentifier withDic:(NSDictionary *)dic
{
self.strActionNotificationType = #"";
if ([strIdentifier isEqualToString:ACCEPT_IDENTIFIER])
{
NSDictionary *apsInfo = [dic objectForKey:#"aps"];
self.strStrRequestId = [apsInfo objectForKey:#"REQUEST_ID"];
self.strActionNotificationType = ACCEPT_PAYMENT_IDENTIFIER;
[self showAlertWithStyle:WKAlertControllerStyleAlert message:EXTENSION_DELGATE.strStrRequestId title:#"Alert"];
}
else if ([strIdentifier isEqualToString:REJECT_IDENTIFIER])
{
// do action for reject payment
NSDictionary *apsInfo = [dic objectForKey:#"aps"];
self.strActionNotificationType =isEqualToString:REJECT_IDENTIFIER;
// do action for accept payment
[self showAlertWithStyle:WKAlertControllerStyleAlert message:EXTENSION_DELGATE.strStrRequestId title:#"Alert"];
}
}
but when i show my strIdentifier in alert view it show empty string.

Get JSON payload data into a string from push notifications

Im trying to get my JSON payload data from a push notification into a string.
{
aps = {
alert = "BG push";
sound = ,
};
}
I researched on SO and on Parse and tried various ways including this Apple Push Notification with Sending Custom Data however my string reruns (null) or as in this example in the JSON format
I want the alert data "BG Push" in a string so I can put this in an alert view
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if ( application.applicationState == UIApplicationStateActive ){
// app was already in the foreground
[PFPush handlePush:userInfo]; //<-----userInfo returns payload data in JSON format
}
else {
// app was just brought from background to foreground
NSLog(#"App was in background and opened from Push message");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Megger"
message: [NSString stringWithFormat:#"%#", userInfo]
delegate:self
cancelButtonTitle: #"Ok"
otherButtonTitles: nil];
[alert show];
}
}
NSString *alert = userInfo[#"aps"][#"alert"];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Megger"
message: [NSString stringWithFormat:#"%#", alert]
delegate:self
cancelButtonTitle: #"Ok"
otherButtonTitles: nil];
[alertView show];
How about
NSDictionary *temp = userInfo[#"aps"];
NSString *message = temp[#"alert"];
If it doesn't work, add this line and let me know what you get
NSLog( #"%#\r%#\r%#", userInfo, temp, message );

SHow image from Push notification in ios sdk

I am new to ios and PNS, i am working on push notification in which i am getting URL in notification based on this i need to show image into image view. i got PNS succesfully also got URL using payload but its not showing in image view in another class
Below is code i am using
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (application.applicationState == UIApplicationStateActive) // If app is running and you got notification then show it
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Did receive a Remote Notification" message:[NSString stringWithFormat:#"You Have a Notification :\n%#",userInfo[#"aps"][#"alert"]]delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
NSLog(#"Payload: %#", userInfo);
imageURL = userInfo[#"aps"][#"alert"];
MainViewController *mv = [[MainViewController alloc] init];
[mv.ansinage setImage:[UIImage imageNamed:#"cartoon.png"]]; // Right now i am setting image in resource but still not setting in mainviewcontrller when i am open app
}
-(void) sshowansimage:(NSString *) strImageURL{
NSURL *imageURL = [NSURL URLWithString:strImageURL];
NSLog(#"coming URL is %#", strImageURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfFile:strImageURL];
[self performSelectorOnMainThread:#selector(showImage:) withObject:imageData waitUntilDone:YES];
});
}
-(void)showImage:(NSData*)imageAsData
{
NSLog(#"IN image view mthhod data is %d",imageAsData.length);
ansinage.image = [UIImage imageWithData:imageAsData];
}

Enable push notifications via a UISwitch

I want to use a UISwitch to enable/disable push notifications. Like in Tweetbot.
Does anyone know how to trigger that?
You can also do it in the following way.
create a IBOutlet for UISwitch
#property (strong, nonatomic) IBOutlet *pushNotificationSwitch;
and in Action method, store the value in NSUserDefaults.
- (IBAction)pushNotificationSwitchChanged:(id)sender
{
NSNumber *switch_value = [NSNumber numberWithBool:[self.pushNotificationSwitch isOn]];
[[NSUserDefaults standardUserDefaults] setObject:switch_value forKey:RECIEVE_APNS];
[[NSUserDefaults standardUserDefaults] synchronize];
}
and check it in viewdidload.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSNumber *sett = [[NSUserDefaults standardUserDefaults] valueForKey:RECIEVE_APNS];
if( [sett boolValue] )
{
[self.pushNotificationSwitch setOn:YES];
}
else{
[self.pushNotificationSwitch setOn:NO];
}
}
and In AppDelegate.m, add the following code
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSNumber *sett = [[NSUserDefaults standardUserDefaults] objectForKey:RECIEVE_APNS];
if( [sett boolValue] )
{
int currentBadgeCount = [[NSUserDefaults standardUserDefaults] integerForKey:#"BadgeCount"];
//Set the baadge count on the app icon in the home screen
int badgeValue = [[[userInfo valueForKey:#"aps"] valueForKey:#"badge"] intValue];
[UIApplication sharedApplication].applicationIconBadgeNumber = badgeValue + currentBadgeCount;
[[NSUserDefaults standardUserDefaults] setInteger:badgeValue + currentBadgeCount forKey:#"BadgeCount"];
NSString *alertString = [[userInfo objectForKey:#"aps"] objectForKey:#"alert"];
NSString *playSoundOnAlert = [NSString stringWithFormat:#"%#", [[userInfo objectForKey:#"aps"] objectForKey:#"sound"]];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%#",[[NSBundle mainBundle] resourcePath],playSoundOnAlert]];
NSError *error;
if (alertString.length > 0)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"App Name" message:alertString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 1;
[audioPlayer play];
[alert show];
}
}
}
enter code here
You can not do that directly from the application. If you want to do this, you need to make the UISwitch send the information to your backend, store this information in your database and stop sending push notifications to this user.
An app registers for Push Notifications (APN) when it first launches. You cannot have it initialize APNs with a switch once it has already launched. You can however code your app that a switch can choose to do "something" with the user interface once a APN is received.
For example, you can have this code:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
// do what you need with the data...
[[NSNotificationCenter defaultCenter] postNotificationName:#"ReceivedNotificationAlert" object:self];
}
You can use your UISwitch to either do something, or not, with the NSNotification "ReceivedNotificationAlert". For example:
if(switchAPNprocess.on){
// process APN
}
else {
// ignore APN
}

Resources