For multiple Alarm Notification Alert?
If Application is Running in Background.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notif{
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
if (application.applicationState == UIApplicationStateInactive )
{
NSLog(#"app not running");
}
else if(application.applicationState == UIApplicationStateActive )
{
NSLog(#"App is running");
}else if(application.applicationState == UIApplicationStateBackground){
NSLog(#"App is running in background");
}
}
In Addition to JAGAT's answer for iOS 8+ you need to ask for permission to register for listening to local notifications. And you can user this:
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler{
}
And for permisson do this:
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
categories:nil]];
}
Use the following method in AppDelegate.m class.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notif{
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
if (application.applicationState == UIApplicationStateInactive )
{
NSLog(#"app not running");
}
else if(application.applicationState == UIApplicationStateActive )
{
NSLog(#"App is running");
}else if(application.applicationState == UIApplicationStateBackground){
NSLog(#"App is running in background");
}
}
May be this is helpful for you to handle local notification in background.
Related
I am working on iOS push notification functionality through apple push notification,right now i am getting proper notification while my app is in background or foreground,but i want to handle remote notification when my app is in background basically when my app is in background it is simply showing alert message from payload.Actually i just want to customize my remote notification.
code:
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions {
// Override point for customization after application launch.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
// [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
}
return YES;
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Did Register for Remote Notifications with Device Token (%#)", error);
}
- (void)application:(UIApplication )application didRegisterForRemoteNotificationsWithDeviceToken:(NSData )deviceToken {
NSLog(#"Did Register for Remote Notifications with Device Token (%#)", deviceToken);
}
-(void)application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo fetchCompletionHandler:(void (UIBackgroundFetchResult))completionHandler
{
NSDictionary * aps=[userInfo valueForKey"aps"];
NSLog(#"did recevie %#",aps);
NSLog(#"userinfo details %#",[aps valueForKey"alert"]);
}
In iOS 10 first you have to set UNUserNotificationCenterDelegate in AppDelegate.h file
#interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate,UNUserNotificationCenterDelegate>
After that in AppDelegate.m write code like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.1) {
// iOS 7.1 or earlier. Disable the deprecation warnings.
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
// iOS 8 or later
// [START register_for_notifications]
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
{
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
[application registerForRemoteNotifications];
} 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) {
}
];
// For iOS 10 display notification (sent via APNS)
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
[[UIApplication sharedApplication] registerForRemoteNotifications];
return YES;
}
Now implement this method for below iOS10 version
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
NSLog(#"Notification received: %#", userInfo);
if( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( #"10.0" ) )
{
NSLog( #"iOS version >= 10. Let NotificationCenter handle this one." );
return;
}
NSLog( #"HANDLE PUSH, didReceiveRemoteNotification: %#", userInfo );
else{
handler( UIBackgroundFetchResultNewData );
}
}
Apple introduces these two methods in iOS10 to receive push notifications.
Write these methods also
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSDictionary *userInfo = notification.request.content.userInfo;
NSLog(#"%#", userInfo);
completionHandler( UNNotificationPresentationOptionAlert );
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
NSLog(#"Userinfo %#",response.notification.request.content.userInfo);
// completionHandler(UNNotificationPresentationOptionAlert);
}
That's it.
Try this
after deploying FCM cloud messaging which is the upgrading version of GCM cloud messaging as mentioned https://developers.google.com/cloud-messaging/ios/client so we moved to integrate FCM in our app using pod as mentioned https://firebase.google.com/docs/cloud-messaging/notifications i follow up every step in the tutorial here is what happening the remote notification had been received well in both state Background State and active state but the main problem that i faced is the notification does appear in the notification bar here is my code that i am using
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
float ver = [[[UIDevice currentDevice] systemVersion] floatValue];
if(ver >= 8 && ver<9)
{
if ([[UIApplication sharedApplication] respondsToSelector:#selector(registerUserNotificationSettings:)])
{
[[UIApplication sharedApplication] registerForRemoteNotifications];
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
}else if (ver >=9){
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else{
//iOS6 and iOS7 specific code
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert];
}
// ma tensa google maps
[FIRApp configure];
[self connectToFcm];
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
NSLog(#"My token is: %#", deviceToken);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
NSLog(#"Failed to get token, error: %#", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.applicationIconBadgeNumber = 0;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.fireDate = [NSDate date];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
NSLog(#"Message ID: %#", userInfo[#"gcm.message_id"]);
//
// if (application.applicationState == active) {
// <#statements#>
// }
// Pring full message.
NSLog(#"%#", userInfo);
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// [[FIRMessaging messaging] disconnect];
}
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"registeredToFCM"];
[[NSUserDefaults standardUserDefaults] synchronize];
// i used the method since not all the time app register for fcm so when
//the complete launching and did not register //
//for fcm the app request to register fro fcm again//
}
}];
}
here some link that i searched for to solve my problem before moving here Notifications are not getting in iOS 9.2 , FCM background notifications not working in iOS, and Push notifications are not working in iOS 9 but i could not solve my issue
Forgot to tell you that the phone is ringing and vibrating when the notification had been received.
hope any one help Happy Coding !!
If you want the notification to show up you have to set "priority":"high". Like so:
"to":"TOKEN ID",
"notification" : {
"body" : "test"
},
"priority": "high"
}
I want to update application badge icon when a notification is received. It works fine when app is running (active mode),but having trouble when trying to set it when app is in suspended/background mode. Want to achieve the same without using the 'badge' field in apns dictionary.
Here is what i am doing,
-(void) incrementOneBadge{
NSInteger numberOfBadges = [UIApplication sharedApplication].applicationIconBadgeNumber;
numberOfBadges +=1;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:numberOfBadges];
}
-(void) decrementOneBadge{ NSInteger numberOfBadges = [UIApplication sharedApplication].applicationIconBadgeNumber;
numberOfBadges -=1;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:numberOfBadges];
}
-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
}
else {
// Push Notification received in the background
[self incrementOneBadge];
}
[self handlePushNotificationsForState:application withDictionary:userInfo];
}
My iOS app stopped receiving push notifications although I upgraded the code as per the documentations and this.
Here's the code I'm using:
In my AppDelegate's didFinishLaunchingWithOptions:
if ([[UIApplication sharedApplication] respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound];
}
The didRegisterForRemoteNotificationsWithDeviceToken method is getting called, as it was before, so everything seems fine.
Also, my test device has the notifications enabled.
But when sending a push from Parse.com it no longer arrives.
EDIT 1:
None of the answers work. I updated my Parse.com framework to version 1.6.2 (the latest) which doesn't help either, and I'm copying my code again - this time the updated version based on the answers:
Inside didFinishLaunchingWithOptions:
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];
// [application registerForRemoteNotifications];
} else {
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[application registerForRemoteNotificationTypes:myTypes];
}
And these are the delegate methods:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken {
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken CALLED");
// Store the deviceToken in the current installation and save it to Parse.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:newDeviceToken];
[currentInstallation addUniqueObject:#"Test8Channel" forKey:#"channels"];
if([PFUser currentUser]/* && [[PFUser currentUser] objectId] != nil*/) {
[currentInstallation addUniqueObject:[PFUser currentUser] forKey:kOwnerKey];
}
[currentInstallation saveInBackground];
}
#ifdef IS_OS_8_OR_LATER
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[application registerForRemoteNotifications];
NSLog(#"didRegisterUserNotificationSettings CALLED");
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString*)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler {
NSLog(#"handleActionWithIdentifier CALLED");
//handle the actions
if ([identifier isEqualToString:#"declineAction"]){
NSLog(#"handleActionWithIdentifier %#", #"declineAction");
}
else if ([identifier isEqualToString:#"answerAction"]){
NSLog(#"handleActionWithIdentifier %#", #"answerAction");
}
}
#endif
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
if (error.code == 3010) {
NSLog(#"Push notifications are not supported in the iOS Simulator.");
} else {
// show some alert or otherwise handle the failure to register.
NSLog(#"application:didFailToRegisterForRemoteNotificationsWithError: %#", error);
}
}
Both didRegisterUserNotificationSettings and didRegisterForRemoteNotificationsWithDeviceToken are getting called and it seems fine. But the push doesn't arrive.
EDIT 2:
I'm noticing that if I call both
[application registerUserNotificationSettings:settings];
and
[application registerForRemoteNotifications];
inside the if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
the delegate's didRegisterForRemoteNotificationsWithDeviceToken is getting called twice. I'm not sure how meaningful this is.
Getting desperate here.
//-- Set Notification
if ([application respondsToSelector:#selector(isRegisteredForRemoteNotifications)])
{
// iOS 8 Notifications
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
}
else
{
// iOS < 8 Notifications
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
}
Use this simple conditional block for handle it. because some methods/classes are updated with version
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
//ios8
if ([[UIApplication sharedApplication] respondsToSelector:#selector(registerUserNotificationSettings:)])
{
UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
.......
}
}
else
{
// ios7
if ([[UIApplication sharedApplication] respondsToSelector:#selector(registerForRemoteNotificationTypes:)])
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
.........
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self enableNotifications:application];
return YES;
}
#define iOS8_OR_NEWER ( [ [ [ UIDevice currentDevice ] systemVersion ] floatValue ] >= 8.0 )
- (void)enableNotifications:(UIApplication *)application
{
if (iOS8_OR_NEWER) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
} else {
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}
}
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
// https://nrj.io/simple-interactive-notifications-in-ios-8
}
#endif
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(#"Push Token : %#", deviceToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Failed to get token, error: %#", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"didReceiveRemoteNotification : %#", userInfo);
}
Just wanted a confirmation. Does the app ask for user permission if i have used silent push notification service like it use to ask when push notification was used. Any help would be appreciated
No. It's silent, meaning it works in the background, without user confirmation at the time of the notification.
At app install it asks for confirmation like a normal push notification.
For silent push you have to set JSON like this (php file),
$body['aps'] = array(
'sound' => '',
'content-available' => 1
);
don't send alert and badge.
In xcode file select target -> capabilities and enable background modes and tick remote notification
in appdelegate.m file just use this message to receive silent push
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
{
//Success this method will automatically call when device receives push notification
handler(UIBackgroundFetchResultNewData);
}
// eg code to register for apps
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];
} else {
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[application registerForRemoteNotificationTypes:myTypes];
}
return YES;
}
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
//register to receive notifications
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
//handle the actions
if ([identifier isEqualToString:#"declineAction"]){
}
else if ([identifier isEqualToString:#"answerAction"]){
}
}
#endif
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(#"My token is: %#", deviceToken);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
NSLog(#"Failed to get token, error: %#", error);
}