In my iOS Application, I want to hide UIAlertView when receiving push notification in didreceiveRemotenotification method.
Whole page of app delegate I am not writting code for show UIAlertView. Then why does it display automatically?
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[PFPush handlePush:userInfo];
if (application.applicationState == UIApplicationStateActive) { self.noti_json=[userInfo objectForKey:#"msg"];
[[NSNotificationCenter defaultCenter] postNotificationName:[userInfo objectForKey:#"title"] object:self];
} }
Thanks in Advance.
Edit (Adding code for my didReceiveRemoteNotification:):
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[PFPush handlePush:userInfo];
if (application.applicationState == UIApplicationStateActive)
{
self.noti_json=[userInfo objectForKey:#"msg"];
[[NSNotificationCenter defaultCenter] postNotificationName:[userInfo objectForKey:#"title"] object:self];
}
}
Remove the line [PFPush handlePush:userInfo];
and show your own alert only if the type is not the one you wanna avoid.
UserInfo must have some identifier or type of notification so that you can handle type specific notifications accordingly.
Handle Push
Edit
Or Simply use below line
if(![[userInfo objectForKey:#"type"] isEqualToString:#"typeName"]){
[PFPush handlePush:userInfo];
}
If you're receiving alerts for Push Notifications it can be due to having the Alerts enabled in settings for your app.
Related
My problem is, if app is in background and notification arrives and I opened the app from icon; app restores it states but I want to update the screen data in this case. Is there any way to update the data in background when notification arrives?
Here is the code which I'm using for tackling this case:
ViewController.m file code:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(appIsComingFromBackground:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void) appIsComingFromBackground:(NSNotification *) note {
// code
NSString *hasMessage = [[NSUserDefaults standardUserDefaults] objectForKey:#"alertmsg"];
if([hasMessage length]!=0)
{
_labelText.text = hasMessage;
[[NSUserDefaults standardUserDefaults] setObject:#"" forKey:#"alertmsg"];
}
else{
_labelText.text = #"";
}
}
AppDelegate.m file code:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
if (application.applicationState == UIApplicationStateActive) {
}
else if(application.applicationState == UIApplicationStateBackground || application.applicationState == UIApplicationStateInactive)
{
[[NSUserDefaults standardUserDefaults] setObject:notification.alertTitle forKey:#"alertmsg"];
}
NSLog(#"Alert Message: %#", notification.alertTitle);
NSLog(#"Alert Body: %#", notification.alertBody);
}
Application is NOT Running
When the app is not running, users see notifications in the following ways, depending on the notification settings:
Displaying an alert or banner
Badging the app icon
Playing a sound
By tapping on action button of the notification, users will launch the app. In this case, the application:didFinishLaunchingWithOptions: method of the application delegate is called.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Handle launching from a notification
UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (locationNotification) {
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
return YES;
}
Applicaton is Running in Foreground
If the app is running while the notification is delivered, there is no alert displayed on screen. The application automatically calls its delegate’s application:didReceiveLocalNotification: method.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
}
// Request to reload table view data
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
Application is Running in Background
The app has been launched before but users switch to another app. When the notification is fired, users normally see an alert banner at the top of the screen. When it’s tapped, the app will be brought to the foreground. Similar to the case that the app is running in foreground, the application automatically calls its delegate’s application:didReceiveLocalNotification: method.
In Appdelegate
- (void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification
{
if (application.applicationState == UIApplicationStateActive) {
}
else if(application.applicationState == UIApplicationStateBackground || application.applicationState == UIApplicationStateInactive)
{
// [[NSUserDefaults standardUserDefaults] setObject:notification.alertTitle forKey:#"alertmsg"];
[[NSNotificationCenter defaultCenter]postNotificationName:#"PushNotificationReceived" object:nil userInfo:userInfo];
}
NSLog(#"Alert Message: %#", notification.alertTitle);
NSLog(#"Alert Body: %#", notification.alertBody);
}
In view controller:
-(void)viewDidLoad
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(doChangesWhatdidYouWant:) name:#"PushNotificationReceived" object:nil];
}
-(void)doChangesWhatdidYouWant:(NSNotification *)notification{
//Todo
}
I am using
userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler
for getting the notification response in iOS 10, can anyone tell me how to get the Application states in it ?
Because in iOS 9 or before I used
application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
In this method, we can get the application state by
application.applicationState
thanks for the help.
You can get application's state from anywhere in your project something like,
UIApplication *applicaiton = [UIApplication sharedApplication];
if (applicaiton.applicationState == UIApplicationStateBackground) {
NSLog(#"background state");
}
same like you can use UIApplicationStateActive,UIApplicationStateInactive etc to get respective state
I did some search and I got these methods
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
NSLog( #"for handling push in foreground" );
// Your code
NSLog(#"%#", notification.request.content.userInfo); //for getting response payload data
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
NSLog( #"for handling push in background" );
// Your code
NSLog(#"%#", notification.request.content.userInfo); //for getting response payload data
}
Something like this:
NSString * state = #"Unknown";
UIApplication *application = [UIApplication sharedApplication];
if ( application.applicationState == UIApplicationStateInactive ) {
//The application received the notification from an inactive state, i.e. the user tapped the "View" button for the alert.
//If the visible view controller in your view controller stack isn't the one you need then show the right one.
state = #"UIApplicationStateInactive";
}
if(application.applicationState == UIApplicationStateActive ) {
//The application received a notification in the active state, so you can display an alert view or do something appropriate.
state = #"UIApplicationStateActive";
}
if(application.applicationState == UIApplicationStateBackground ) {
state = #"UIApplicationStateBackground";
}
I am using following code to handle push notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
if(application.applicationState == UIApplicationStateInactive)
{
//************************************************************
// I only want this called when user click on notification.
//************************************************************
NSLog(#"Inactive");
if ([[userInfo valueForKey:#"noty_type"] isEqualToString:#"web"])
{
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[userInfo valueForKey:#"url"]]])
{
dispatch_async(dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[userInfo valueForKey:#"url"]]];
});
}
}
}
if((application.applicationState == UIApplicationStateActive)
{
// I am useing local notification when app in Forground
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.soundName = #"Default";
localNotification.alertBody = [userInfo valueForKey:#"msg"];
localNotification.userInfo = userInfo;
[[UIApplication sharedApplication] scheduleLocalNotification: localNotification];
}
}
This code open the url in safari browser. this code work fine When my app in background and notification come and I click on notification check the applicationState and open the url with [[UIApplication sharedApplication] openURL.
now the scenario that generate the problem.
I open my app .
and Down the notification UI
now Send the notification from server
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler method get called.
Now I get the ApplicationState == UIApplicationStateInactive .
"It open into the safari browser without any user interaction".
I only want this called when user click on notification.
So, How can I handle this condition ?
Try this.
if (application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground)
{
// do something when app open with notification
}
You have to know why the app is inactive. The two possibilities are that the app was in the background and the user is bringing it to the foreground (by tapping on the notification banner), or something like the notification center was pulled down or the user got a system alert.
To tell the difference, keep track of when the user enters the background. Just set a boolean in the applicationDidEnterBackground: delegate method, and clear it when the app is resigning active.
static BOOL didEnterBackground;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Launching the app is kind of like coming from background.
didEnterEnterBackground = YES;
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
didEnterBackground = NO;
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
didEnterBackground = YES;
}
Now you can check the variable didEnterBackground to determine how the app got to the inactive state when you're handling a notification.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if (application.applicationState == UIApplicationStateInactive) {
if (didEnterBackground) {
// The user tapped the notification
}
else {
// The app was inactive, but not in the background.
// Ignore notification, or do whatever the app does
// when receiving a notification while active.
}
}
}
Hope this help you
-(void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
}//iOS below 9
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(nullable NSString *)identifier
forLocalNotification:(nonnull UILocalNotification *)notification
completionHandler:(nonnull void (^)())completionHandler {
// handling local and interactive notifcation
} // iOS 9 and above
Which is used to trigger the notification in background state.
when my app receives a push notification I want to increment a variable i.e. totalMessages++. I know that :
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[PFPush handlePush:userInfo];
}
is called when a push is received and the app is currently open. However this is declared in AppDelegate.m. How would I modify a variable in the currently displayed view controller i.e. FriendDisplayViewController?
You may want to begin by handling the notification & payload (read: userInfo) yourself, e.g.:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[NSNotificationCenter defaultCenter] postNotificationName:superUniqueNotificationName
object:nil
userInfo:userInfo];
}
For the appDelegate & your viewController to use the same notificationName, you'll want to share it somewhere centrally (e.g.: AwesomeConstants.h/.m):
FOUNDATION_EXTERN NSString * const superUniqueNotificationName; // .h
NSString * const superUniqueNotificationName = #"superUniqueNotificationName"; // .m
Leaving your viewController to include something like
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receivedParseNotification:)
name:superUniqueNotificationName
object:nil];
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)receivedParseNotification:(NSNotification *)parseNotification {
NSLog(#"got %# in FriendDisplayViewController, let's rock some variables", parseNotification);
}
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.. :)