当您的应用程序打开并处于前台时显示股票 iOS 通知横幅?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30852870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying a stock iOS notification banner when your app is open and in the foreground?
提问by pkamb
When Apple's official iOS Messages app is open and in the foreground, new messages from other contacts trigger a stock, native iOS notification alert banner. See image below.
当 Apple 的官方 iOS 消息应用程序打开并处于前台时,来自其他联系人的新消息会触发一个股票的原生 iOS 通知警报横幅。见下图。
Is this possible in 3rd party apps on the App Store? Local and/or Push Notifications for your app while your app is open and in the foreground?
这在 App Store 的第 3 方应用程序中是否可行?当您的应用程序处于打开状态和在前台时,您的应用程序的本地和/或推送通知?
When testing my app, notifications are received but no iOS alert UI is shown.
测试我的应用程序时,会收到通知,但没有显示 iOS 警报 UI。
But this behavior isseen in Apple's official Messages app:
但是在 Apple 的官方消息应用程序中可以看到这种行为:
The Local and Remote Notification Programming Guidesays:
在本地和远程通知编程指南说:
When the operating system delivers a local notification or remote notification and the target app is not running in the foreground, it can present the notification to the user through an alert, icon badge number, or sound.
If the app is running in the foregroundwhen the notification is delivered, the app delegate receives a local or remote notification.
当操作系统传递本地通知或远程通知并且目标应用程序未在前台运行时,它可以通过警报、图标徽章编号或声音向用户呈现通知。
如果在传递通知时应用程序在前台运行,则应用程序委托会收到本地或远程通知。
So yes, we can receive the notification datawhile in the foreground. But I see no way to present the native iOS notification alert UI.
所以是的,我们可以在前台接收通知数据。但我看不到本机 iOS 通知警报 UI 的呈现方式。
-(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]
}
Is Messages then using a private API to display the alert while in the foreground?
Messages 然后使用私有 API 在前台显示警报吗?
For the purpose of this question, please do not suggest any 3rd party "toast" pop-up alertson github or etc. I'm only interested if this can be done using the stock, native iOSLocal or Push Notification alerts UI while your application is open and in the foreground.
对于这个问题的目的,请不要提出任何第三方“敬酒”,弹出警报在github上或者等我只是有兴趣,如果这可以用做库存,提供原生iOS本地或推送通知提醒用户界面,而你应用程序已打开并处于前台。
回答by pkamb
iOS 10adds the UNUserNotificationCenterDelegate
protocol for handling notifications while your app is in the foreground.
iOS 10添加了UNUserNotificationCenterDelegate
在您的应用程序处于前台时处理通知的协议。
The
UNUserNotificationCenterDelegate
protocol defines methods for receiving notifications and for handling actions. When your app is in the foreground, arriving notifications are delivered to your delegate object instead of displayed automatically using the system interfaces.
该
UNUserNotificationCenterDelegate
协议定义了接收通知和处理操作的方法。当您的应用程序在前台时,到达的通知将传递给您的委托对象,而不是使用系统界面自动显示。
Swift:
迅速:
optional func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
Objective-C:
目标-C:
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler;
The UNNotificationPresentationOptionsflags allow you to specify UNNotificationPresentationOptionAlert
to display an alert using the text provided by the notification.
该UNNotificationPresentationOptions标志允许您指定UNNotificationPresentationOptionAlert
显示使用通知中的文本警报。
This is key as it allows you to display the alert while your app is open and in the foreground, which is new for iOS 10.
这是关键,因为它允许您在应用程序打开时在前台显示警报,这是 iOS 10 的新功能。
Sample code:
示例代码:
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Set UNUserNotificationCenterDelegate
UNUserNotificationCenter.current().delegate = self
return true
}
}
// Conform to UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler(.alert)
}
}
回答by chengsam
For displaying banner message while app is in foreground, use the following method.
要在应用程序处于前台时显示横幅消息,请使用以下方法。
iOS 10+, Swift 3+:
iOS 10+,Swift 3+:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
回答by pkamb
EDIT:
编辑:
Foreground alerts are now possible in iOS 10! Please see this answer.
现在可以在 iOS 10 中使用前景警报!请看这个答案。
For iOS 9 and below:
对于 iOS 9 及以下:
It does not seem to be possible to show the stock iOS notification alert when your app is open and in the foreground. Messages.app must be using a private API.
当您的应用程序打开并处于前台时,似乎无法显示股票 iOS 通知警报。Messages.app 必须使用私有 API。
The system does not display any alerts, badge the app's icon, or play any sounds when the app is already frontmost. - UILocalNotification docs
当应用程序已经在最前面时,系统不会显示任何警报、标记应用程序图标或播放任何声音。- UILocalNotification 文档
The UIApplicationDelegate
methods willstill be called, allowing your app to respond to the local or remote notification:
该UIApplicationDelegate
方法将仍然被调用,让您的应用程序以应对本地或远程通知:
application:didReceiveLocalNotification:
application:didReceiveRemoteNotification:
However, the stock native iOS notification alert banner UI will not be shownas it is in Apple's Messages.app, which must be using a Private API.
但是,股票原生 iOS 通知警报横幅 UI不会像在 Apple 的 Messages.app 中那样显示,它必须使用私有 API。
The best you can do is is roll your own alert banner or use an existing framework:
您能做的最好的事情是滚动您自己的警报横幅或使用现有框架:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
// Use a 3rd party toast alert framework to display a banner
[self toastAlertFromGithub]
}
I have opened a radar for this behavior here: rdar://22313177
我在这里为这种行为打开了雷达: rdar://22313177
回答by Hafeez
To show notifications while the App is open, we need to handle it manually. So what I am doing below is to handle the notification once received.
要在应用程序打开时显示通知,我们需要手动处理它。所以我在下面做的是处理收到的通知。
Add all below in AppDelegate.m
在 AppDelegate.m 中添加以下所有内容
- Handle call for notify
- Create a view, add AppIcon, Notification message and show it as an animation
- Add Touch recogniser to remove if touched or remove in 5 seconds with animation.
- 处理通知调用
- 创建一个视图,添加 AppIcon、通知消息并将其显示为动画
- 添加触摸识别器以在触摸时移除或在 5 秒内移除动画。
Let me know if this is an ok solution. Worked well for me but am unsure 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) {
}];
}
回答by Kavin Kumar Arumugam
Here is the code to receive Push Notification when app in foreground or in open stage, iOS 10 & Swift 2.3
这是当应用程序处于前台或打开阶段时接收推送通知的代码,iOS 10 和 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 of notification use code: notification.request.content.userInfo
如果您需要访问通知使用代码的 userInfo: notification.request.content.userInfo
The method userNotificationCenter(_:willPresent:withCompletionHandler:)
is only called if you add to payload the attribute content-available:1
. The final payload should be something like:
userNotificationCenter(_:willPresent:withCompletionHandler:)
仅当您将属性添加到有效负载时才会调用该方法content-available:1
。最终的有效载荷应该是这样的:
{
"aps":{
"alert":"Testing.. (7)",
"badge":1,"sound":"default"
},
"content-available":1
}
回答by Nguyen Loc
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 push notification when app is active for iOS 10.
我可以在iOS 10 的应用程序处于活动状态时显示推送通知。
The push notification from server should be silent.
When receive remote notification from server, you send a local notification and set the value for keyPath: shouldAlwaysAlertWhileAppIsForeground = True
来自服务器的推送通知应该是静默的。
当从服务器接收远程通知时,您发送本地通知并设置keyPath的值: shouldAlwaysAlertWhileAppIsForeground = True
回答by Mo Farhand
You can handle the notification yourself and show a custom alert. Apps such as Viber, Whatsapp, and BisPhone use this approach.
您可以自己处理通知并显示自定义警报。Viber、Whatsapp 和 BisPhone 等应用程序使用这种方法。
One example of a 3rd party custom alert is CRToast.
第 3 方自定义警报的一个示例是CRToast。
Try scheduling a local notification while your app is in the foreground, and you will see that no stock iOS alert is shown:
尝试在您的应用程序处于前台时安排本地通知,您将看到没有显示任何股票 iOS 警报:
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];
}
回答by Leslie Godwin
Swift 3 version
斯威夫特 3 版本
This shows an alert 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)")
}
}
ApplicationDelegate's implementation of UNUserNotificationCenterDelegate
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
}
回答by Vishwas Singh
If your deployment target >= iOS10, use UNUserNotification like below-
如果您的部署目标 >= iOS10,请使用 UNUserNotification,如下所示-
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
// Change this to your preferred presentation option
completionHandler([.alert, .sound])
}
回答by Mantosh Kumar
To show local Notification this is the best option . need less code to wright "BRYXBanner " https://cocoapods.org/pods/BRYXBanner
要显示本地通知,这是最好的选择。需要更少的代码来编写“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)