Get push notification while App in foreground iOS
For displaying banner message while app is in foreground, use the following method.
iOS 10, Swift 3/4 :
// This method will be called when app received push notifications in foregroundfunc userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound])}
iOS 10, Swift 2.3 :
@available(iOS 10.0, *)func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void){ //Handle the notification completionHandler( [UNNotificationPresentationOptions.Alert, UNNotificationPresentationOptions.Sound, UNNotificationPresentationOptions.Badge])}
You must also register your app delegate as the delegate for the notifications center:
import UserNotifications// snip!class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate// snip! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // set the delegate in didFinishLaunchingWithOptions UNUserNotificationCenter.current().delegate = self ... }
Below code will be work for you :
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { application.applicationIconBadgeNumber = 0; //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) { // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view. 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]; } }
Objective C
For iOS 10
we need integrate willPresentNotification
method for show notification banner in foreground
.
If app in foreground mode(active)
- (void)userNotificationCenter:(UNUserNotificationCenter* )center willPresentNotification:(UNNotification* )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { NSLog( @"Here handle push notification in foreground" ); //For notification Banner - when app in foreground completionHandler(UNNotificationPresentationOptionAlert); // Print Notification info NSLog(@"Userinfo %@",notification.request.content.userInfo);}