Push Notification works only once - ios

The push notification only works when the app is in background ,But it didn't work when i removed it from background also when it returned to background , i didn't receive any push notifications. I had to delete the app and download it again from testflight to be able to receive push notifications.
here's the code
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
//Do stuff that you would do if the application was not active
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSLog(#"Aps Info : %#",apsInfo);
NSString *alert = [apsInfo objectForKey:#"alert"];
NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
#endif
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
NSInteger pushCode = [userInfo[#"pushCode"] integerValue];
NSLog(#"Silent Push Code Notification: %i", pushCode);
NSDictionary *aps = userInfo[#"aps"];
NSString *typeID = userInfo[#"type_id"];
NSString *alertMessage = aps[#"alert"];
NSLog(#"Type ID %#",typeID);
NSArray * array =[typeID componentsSeparatedByString:#","];
NSLog(#"Item %#,Item2 %#",[array objectAtIndex:0],[array objectAtIndex:1]);
[self typeID:[array objectAtIndex:0] userID:[array objectAtIndex:1] message:alertMessage];
NSLog(#"apss%#,alert%#,%#",aps,alertMessage,userInfo);
}

The problem is in the method:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
}
you should "catch" the notifications which arrive in background with this method:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
}
the fetchCompletionHandler method is designed for receiving "silent" push messages, which gets called prior to didReceiveRemoteNotification, if implemented.

Related

Firebase messaging works only in foreground

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
[FIRMessaging messaging].remoteMessageDelegate = self;
[[UIApplication sharedApplication] registerForRemoteNotifications];
[FIRApp configure];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[FIRMessaging messaging] disconnect];
NSLog(#"Disconnected from FCM");
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[self connectToFcm];
}
- (void)applicationWillTerminate:(UIApplication *)application {
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Print message ID.
NSLog(#"message 1");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Print message ID.
NSLog(#"message 2");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
NSLog(#"%#", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSLog(#"message 3");
NSDictionary *userInfo = notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
NSLog(#"full data : %#", userInfo);
completionHandler(UNNotificationPresentationOptionAlert);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler {
NSDictionary *userInfo = response.notification.request.content.userInfo;
NSLog(#"message 1");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
completionHandler();
}
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
// Print full message
NSLog(#"applicationReceivedRemoteMessage : %#", remoteMessage.appData);
}
- (void)tokenRefreshNotification:(NSNotification *)notification {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
NSLog(#"InstanceID token: %#", refreshedToken);
if(!(refreshedToken== nil)){
[defaults setValue:refreshedToken forKey:#"FcmToken"];
}
[self connectToFcm];
}
- (void)connectToFcm {
if (![[FIRInstanceID instanceID] token]) {
return;
}
[[FIRMessaging messaging] disconnect];
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
}
}];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Unable to register for remote notifications: %#", error);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"APNs token retrieved: %#", deviceToken);
}
enter code here
When app is in the background mode, message not coming. When app is running foreground mode message shows in applicationReceivedRemoteMessage function. I need to run some code when message comes when background mode. Can anyone give me the solution for get the notifications works in background mode.
FIRMessaging connection won’t be allowed to live when in background it
is prudent to close the connection.
Please find here reference for the same: disconnect()
FirebaseMessaging Framework Reference
Simple Logic About Chat Applications: Socket Connection
Generally, Chat applications connects with other nodes (devices) using socket connection to transmit real-time information between nodes. Socket connections are disconnected, when apps goes into background.
FirebaseMessaging works on same logic and hence is won't work in background.
To handle message transmission in background mode, use power of PushNotification.
Also mark your code: You are disconnecting FIRMessaging when application goes into background. And you've done this, because the same is instructed in FIRMessaging guidelines.
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[FIRMessaging messaging] disconnect];
NSLog(#"Disconnected from FCM");
}
As an alternate solution of your problem: You may have analyzed Whatapp or Facebook Messagner app. They use push notification to alert user for messages, when app goes into background. You should do the same.

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

Is there a way to open urls received in a push notification without opening the app in ios 10?

I am trying to open a url that is passed in a push notification in ios 10.
So far I haven't found a way to open a the url without opening the app.
Is there a way to open urls received in a push notification without opening the app?
I have found a work-around to open the url (the work-around works for ios <10), but then again the app opens up first.
Update:
I've noticed that for the device (iOS 10.0)
The following mentohds get involked
application:didRegisterForRemoteNotificationsWithDeviceToken
userNotificationCenter:willPresentNotification:
userNotificationCenter:didReceiveNotificationResponse:
But -application:didReceiveRemoteNotification:fetchCompletionHandler: and -application:didReceiveRemoteNotification: aren't called.
I'm new to ios and this is how far I have gotten:
AppDelegate.h
#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
#property (strong, nonatomic) UIWindow *window;
#end
AppDelegate.m
#import "AppDelegate.h"
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10)
{
UNUserNotificationCenter * notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
notificationCenter.delegate = self;
[notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * error)
{
[[UIApplication sharedApplication] registerForRemoteNotifications];
if (error)
{
NSLog(#"Auth. error:%#",[error localizedDescription]);
}
}];
[notificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * settings) {
}];
}
else
{
UIUserNotificationType type = UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound;
UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
return YES;
}
...
#pragma mark Push Notification methods
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(#"didReceiveRemoteNotification:");
NSString * message = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
NSString * urlString = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
NSLog(#"1 Received Push URL: %#", urlString);
NSURL * url = [NSURL URLWithString:urlString];
if(url!=nil)
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
// iOS 10 and above
[[UIApplication sharedApplication] openURL:url options:[NSDictionary dictionary] completionHandler:nil];
}
else
{
[[UIApplication sharedApplication] openURL:url]; // iOS <10
}
}
if (application.applicationState == UIApplicationStateInactive)
{
NSLog(#"Application inactive");
[[NSUserDefaults standardUserDefaults] setValue:message forKey:#"Push_Message"];
}
else if (application.applicationState == UIApplicationStateBackground)
{
NSLog(#"Application in background");
}
else
{
NSLog(#"Application active");
}
}
#pragma mark Notification Registration methods
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString* token = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: #"<" withString: #""]
stringByReplacingOccurrencesOfString: #">" withString: #""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken:\n%#",token);
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Error:%#",[error localizedDescription]);
NSLog(#"Suggest:%#",[error localizedRecoverySuggestion]);
}
#pragma mark App Push notification methods
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
NSLog(#"didRegisterUserNotificationSettings");
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"UserInfo: %#",userInfo);
NSString * messageString = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
NSLog(#"Message:%#",messageString);
NSString * messageurl = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
NSLog(#"2 Received Push URL: %#", messageurl);
NSURL * url = [NSURL URLWithString:messageurl];
if(url!=nil)
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
// iOS 10 and above
[[UIApplication sharedApplication] openURL:url options:[NSDictionary dictionary] completionHandler:nil];
}
else
{
[[UIApplication sharedApplication] openURL:url]; // iOS <10
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"PushMessage" object:self userInfo:#{#"alertString":messageString}];
}
#pragma mark UNUserNotificationCenterDelegate methods
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
NSLog(#"didReceiveNotificationResponse");
//--URL click--//
//Kindly suggest what can be done here?
completionHandler(UNNotificationPresentationOptionAlert);
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
NSLog(#"willPresentNotification");
completionHandler(UNNotificationPresentationOptionAlert);
}
#end
Hopefully you can't control the behaviour of the push before launching the app. You get control over the push only after the app launched.

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

Parse pushnotificaton not displaying in iOS?

I have configured parse and send pushnotification form there (both plain text and json)
then inside my project this methode get called
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
{
if (application.applicationState == UIApplicationStateInactive)
{
[PFAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
}
[PFPush handlePush:userInfo];
NSLog(#"----notify-->%#",userInfo);
sharedManager=[Mymanager sharedManager];
THNotificationData *newNotification=[[THNotificationData alloc] init];
newNotification.notificationDetails = [userInfo objectForKey:#"description"];
NSLog(#"%#",[userInfo objectForKey:#"description"]);
newNotification.notificationTitle = [userInfo objectForKey:#"title"];
newNotification.notificationURL = [userInfo objectForKey:#"url"];
sharedManager.notificationTitle=[userInfo objectForKey:#"title"];
sharedManager.notificationDetails=[userInfo objectForKey:#"description"];
sharedManager.notificationURL=[userInfo objectForKey:#"url"];
newNotification.isRead = NO;
newNotification.timeStamp = timestamp;
[notificationStore addNotificationData:newNotification];
[[NSNotificationCenter defaultCenter] postNotificationName:kParseNotificationKey object:nil userInfo:userInfo];
}
i can see then message in log also but after that i got warning in log
"2015-01-07 11:26:08.991 PROJECT[325:35376] Warning: Application delegate received call to -application:didReceiveRemoteNotification:fetchCompletionHandler: but the completion handler was never called."
and it didnt showing notification in phone(as a popup or alert).
please help me
You have to implement this (Its just an example method):
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
if(application.applicationState == UIApplicationStateInactive) {
NSLog(#"Inactive");
completionHandler(UIBackgroundFetchResultNewData);
} else if (application.applicationState == UIApplicationStateBackground) {
NSLog(#"Background");
completionHandler(UIBackgroundFetchResultNewData);
} else {
NSLog(#"Active");
completionHandler(UIBackgroundFetchResultNewData);
}
}
Hope this helps.. :)

Resources