Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push notification Doesnt work when the Application is running(Active) [duplicate]

Tags:

ios

iphone

ipad

Im working on a simple application with push notification and I successfully implemented it. When I exit the application, Im getting a push notification(Works well) but when I open the app and try to send a message from my server(Web application), It doesn't display any popup message or notification on it. Did I missed something? Here is my code snippet on AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  {

// Let the device know we want to receive push notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
 (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
 return YES;
 }


 (void)application:(UIApplication*)application didReceiveRemoteNotification: (NSDictionary*)userInfo{
  NSLog(@"Received notification: %@", userInfo);
  NSString *messageAlert = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
  NSLog(@"Received Push Badge: %@", messageAlert );
  [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification" object:messageAlert];

 }

Please help me regarding this. Thanks.

like image 217
user2656044 Avatar asked Jan 26 '26 19:01

user2656044


1 Answers

When you app is Active Mode you need to put this method something like bellow into your Appdelegate class:-

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {    
    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateActive) {
        NSString *cancelTitle = @"Close";
        NSString *showTitle = @"Show";
        NSString *message = [[userInfo valueForKey:@"aps"] valueForKey:@"alert"];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"My App Name"
                                                            message:message 
                                                           delegate:self 
                                                  cancelButtonTitle:cancelTitle 
                                                  otherButtonTitles:showTitle, nil];
        [alertView show];
        [alertView release];


    } else {
        //Do stuff that you would do if the application was not active
    }
}   

Also put didFailToRegisterForRemoteNotificationsWithError delegate for checking Fail Reason

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
 NSString *str = [NSString stringWithFormat: @"Error: %@", error];
    NSLog(@"%@", str);
} 
like image 80
Nitin Gohel Avatar answered Jan 28 '26 08:01

Nitin Gohel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!