Displaying iOS notification icon banner when your application is open and in the foreground?

When the Apple application officially published the iOS application is open, and in the foreground new messages from other contacts launch stockpiles, iOS notification notification banner of its own. See image below.

Is this possible in third-party apps on the App Store? Local and / or push notifications for your application when your application is open and in the foreground ?

When testing my application, notifications are received, but the iOS user ID is not displayed .

But this behavior displayed in Apple's official messaging app:

Messages is open and in the foreground. Still shows a notification alert.

The local and remote notification programming guide reports:

When the operating system sends a local notification or remote notification, and the target application does not work in the foreground , it can send a notification to the user through alert , icon icon number or sound.

If the application runs in the foreground when the notification is delivered, the application delegate receives a local or remote notification.

So yes, we can receive notification data in the foreground. But I do not see the opportunity to present the iOS notification notification user interface .

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // I know we still receive the notification `userInfo` payload in the foreground. // This question is about displaying the stock iOS notification alert UI. // Yes, one *could* use a 3rd party toast alert framework. [self use3rdPartyToastAlertFrameworkFromGithub] } 

Are messages using the private API used to display a warning in the foreground?

For the purpose of this question , please do not offer any third-party toast alerts on github, etc. I'm only interested in this if it can be done using the iOS Inventory Local or Push Notification UI when your application is open and in the foreground.

+59
ios uikit toast apple-push-notifications uilocalnotification
Jun 15 '15 at 18:52
source share
10 answers

iOS 10 adds the UNUserNotificationCenterDelegate protocol for handling notifications when your application is in the foreground.

The UNUserNotificationCenterDelegate protocol defines methods for receiving notifications and handling actions. When your application is in the foreground, incoming notifications are delivered to the delegate object instead of being automatically displayed using system interfaces.

Swift:

 optional func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) 

Objective-C:

 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler; 

The UNNotificationPresentationOptions flags let you specify a UNNotificationPresentationOptionAlert to display a warning using the text provided by the notification.

This is the key, as it allows you to display a warning while your application is open and in the foreground , which is new to iOS 10.

Code example:

 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) } 
+67
Jun 15 '16 at 19:38
source share

To display a banner message when the application is in the foreground, use the following method.

iOS 10, Swift 3 :

 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(UNNotificationPresentationOptions.alert) } 
+51
Nov 23 '16 at 4:30
source share

To show notifications while the application is open, we must process it manually. So, what I do below, you need to process the notification after receiving it.

Add all below to AppDelegate.m

  • Refer to Notification
  • Create a view, add the AppIcon message, Notification, and show it as an animation.
  • Add Touch Recognizer to remove if it is touched or removed in 5 seconds with animation.

Let me know if this is an approved solution. Worked well for me, but I'm not sure if this is the right way.

 - (void)application:(UIApplication *)applicationdidReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { NSString *notifMessage = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]; //Define notifView as UIView in the header file [_notifView removeFromSuperview]; //If already existing _notifView = [[UIView alloc] initWithFrame:CGRectMake(0, -70, self.window.frame.size.width, 80)]; [_notifView setBackgroundColor:[UIColor blackColor]]; UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10,15,30,30)]; imageView.image = [UIImage imageNamed:@"AppLogo.png"]; UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 15, self.window.frame.size.width - 100 , 30)]; myLabel.font = [UIFont fontWithName:@"Helvetica" size:10.0]; myLabel.text = notifMessage; [myLabel setTextColor:[UIColor whiteColor]]; [myLabel setNumberOfLines:0]; [_notifView setAlpha:0.95]; //The Icon [_notifView addSubview:imageView]; //The Text [_notifView addSubview:myLabel]; //The View [self.window addSubview:_notifView]; UITapGestureRecognizer *tapToDismissNotif = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissNotifFromScreen)]; tapToDismissNotif.numberOfTapsRequired = 1; tapToDismissNotif.numberOfTouchesRequired = 1; [_notifView addGestureRecognizer:tapToDismissNotif]; [UIView animateWithDuration:1.0 delay:.1 usingSpringWithDamping:0.5 initialSpringVelocity:0.1 options:UIViewAnimationOptionCurveEaseIn animations:^{ [_notifView setFrame:CGRectMake(0, 0, self.window.frame.size.width, 60)]; } completion:^(BOOL finished) { }]; //Remove from top view after 5 seconds [self performSelector:@selector(dismissNotifFromScreen) withObject:nil afterDelay:5.0]; return; } //If the user touches the view or to remove from view after 5 seconds - (void)dismissNotifFromScreen{ [UIView animateWithDuration:1.0 delay:.1 usingSpringWithDamping:0.5 initialSpringVelocity:0.1 options:UIViewAnimationOptionCurveEaseIn animations:^{ [_notifView setFrame:CGRectMake(0, -70, self.window.frame.size.width, 60)]; } completion:^(BOOL finished) { }]; } 
+12
May 30 '16 at 12:08
source share

Here is the code for getting Push Notification when applying in the foreground or in an open scene, iOS 10 and Swift 2.3

 @available(iOS 10.0, *) func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { completionHandler([UNNotificationPresentationOptions.Alert,UNNotificationPresentationOptions.Sound,UNNotificationPresentationOptions.Badge]) } 

If you need to access userInfo notification usage code: notification.request.content.userInfo

The userNotificationCenter(_:willPresent:withCompletionHandler:) is called only if you add the content-available:1 attribute to the payload. The final payload should be something like this:

 { "aps":{ "alert":"Testing.. (7)", "badge":1,"sound":"default" }, "content-available":1 } 
+10
Dec 27 '16 at 9:23
source share

EDIT:

Foreground alerts are now available on iOS 10! See this answer .

For iOS 9 and below:

It seems that it is not possible to show an iOS notification notification in stock when your application is open and in the foreground. Message.app must use a private API.

The system does not display warnings, the icon of the application icon, or playing any sounds when the application is already in the foreground. - UILocalNotification documents

UIApplicationDelegate methods will now be called, allowing your application to respond to local or remote notifications:

 application:didReceiveLocalNotification: application:didReceiveRemoteNotification: 

However, the iOS-based alert notification user interface will not be displayed as specified in Apple Messages.app, which should use a private API.

The best you can do is minimize your own alert banner or use your existing infrastructure:

 -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // Use a 3rd party toast alert framework to display a banner [self toastAlertFromGithub] } 

I discovered here a radar for this behavior: rdar: // 22313177

+9
Jun 15 '15 at 10:12
source share
 UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.body = body; content.userInfo = userInfo; content.sound = [UNNotificationSound defaultSound]; [content setValue:@(YES) forKeyPath:@"shouldAlwaysAlertWhileAppIsForeground"]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"Notif" content:content trigger:nil]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { DLog(@"Error:%@", error); }]; 

I can show a push notification when the application is active for iOS 10.

  • The pressed notification from the server should be quiet .

  • When you receive a remote notification from the server, you send a local notification and set the value for keyPath: shouldAlwaysAlertWhileAppIsForeground = True

+7
Nov 22 '16 at 16:32
source share

You can independently process the notification and show your own notification. Applications such as Viber, Whatsapp and BisPhone use this approach.

One example of a third-party custom alert is CRToast .

Try planning a local notification when your application is in the foreground and you will see that the iOS warning message is not displayed:

 if (application.applicationState == UIApplicationStateActive ) { UILocalNotification *localNotification = [[UILocalNotification alloc] init]; localNotification.userInfo = userInfo; localNotification.soundName = UILocalNotificationDefaultSoundName; localNotification.alertBody = message; localNotification.fireDate = [NSDate date]; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; } 
+3
Jun 15 '15 at 19:08
source share

version of Swift 3

This shows a warning when the application is in the foreground.

 if #available(iOS 10.0, *) { // need to setup the global notification delegate somewhere when your app starts // UNUserNotificationCenter.current().delegate = applicationDelegate // to show a message // let content = UNMutableNotificationContent() content.body = "MESSAGE" let request = UNNotificationRequest(identifier: "fred", content: content, trigger: nil) UNUserNotificationCenter.current().add(request) { error in // called when message has been sent debugPrint("Error: \(error)") } } 

Using ApplicationDelegate UNUserNotificationCenterDelegate

 @available(iOS 10.0, *) public func userNotificationCenter(_ center : UNUserNotificationCenter, willPresent notification : UNNotification, withCompletionHandler completionHandler : @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert]) // only-always show the alert } 
+3
Jun 06 '17 at 8:39 on
source share

To show a local notification, this is the best option. need less code for "BRYXBanner" https://cocoapods.org/pods/BRYXBanner

 let banner = Banner(title: "title", subtitle: "subtitle", image: UIImage(named: "addContact"), backgroundColor: UIColor(red:137.0/255.0, green:172.0/255.0, blue:2.0/255.0, alpha:1.000)) banner.dismissesOnTap = true banner.show(duration: 1.0) 
0
Oct 06 '16 at 11:06
source share

If the deployment target is> = iOS10, use UNUserNotification as shown below -

 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // Change this to your preferred presentation option completionHandler([.alert, .sound]) } 
0
Dec 11 '17 at 11:18
source share



All Articles