应用在前台 iOS 时获取推送通知
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14872088/
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
Get push notification while App in foreground iOS
提问by Ab'initio
I am using push notification service in my app. When app is in background I am able to see notification on notification screen(screen shown when we swipe down from top of iOS device). But if application is in foreground the delegate method
我在我的应用程序中使用推送通知服务。当应用程序在后台时,我可以在通知屏幕上看到通知(当我们从 iOS 设备顶部向下滑动时显示的屏幕)。但是如果应用程序在前台,则委托方法
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
is getting called but notification is not displayed in notification screen.
正在被调用,但通知屏幕中未显示通知。
I want to show notification on notification screen independent of whether app is in background or foreground. I am tired by searching for a solution. Any help is greatly appreciated.
我想在通知屏幕上显示通知,而不管应用程序是在后台还是前台。我厌倦了寻找解决方案。任何帮助是极大的赞赏。
采纳答案by Ab'initio
If the application is running in the foreground, iOS won't show a notification banner/alert. That's by design. But we can achieve it by using UILocalNotification
as follows
如果应用程序在前台运行,iOS 将不会显示通知横幅/警报。那是设计使然。但是我们可以通过UILocalNotification
如下方式实现
Check whether application is in active state on receiving a remote
notification. If in active state fire a UILocalNotification.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]; }
检查应用程序是否在收到远程
通知时处于活动状态。如果处于活动状态,则触发 UILocalNotification。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]; }
SWIFT:
迅速:
if application.applicationState == .active {
var localNotification = UILocalNotification()
localNotification.userInfo = userInfo
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.alertBody = message
localNotification.fireDate = Date()
UIApplication.shared.scheduleLocalNotification(localNotification)
}
回答by chengsam
For displaying banner message while app is in foreground, use the following method.
要在应用程序处于前台时显示横幅消息,请使用以下方法。
iOS 10, Swift 3/4:
iOS 10,Swift 3/4:
// This method will be called when app received push notifications in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert, .badge, .sound])
}
iOS 10, Swift 2.3:
iOS 10,斯威夫特 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
...
}
回答by Mahesh Peri
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];
}
}
回答by Aviel Gross
For anyone might be interested, I ended up creating a custom view that looks like the system push banner on the top but adds a close button (small blue X) and an option to tap the message for custom action. It also supports the case of more than one notification arrived before the user had time to read/dismiss the old ones (With no limit to how many can pile up...)
对于任何可能感兴趣的人,我最终创建了一个自定义视图,它看起来像顶部的系统推送横幅,但添加了一个关闭按钮(蓝色小 X)和一个选项来点击消息以进行自定义操作。它还支持在用户有时间阅读/关闭旧通知之前到达多个通知的情况(没有限制可以堆积多少......)
Link to GitHub: AGPushNote
GitHub 链接:AGPushNote
The usage is basically on-liner:
用法基本上是在线的:
[AGPushNoteView showWithNotificationMessage:@"John Doe sent you a message!"];
And it looks like this on iOS7 (iOS6 have an iOS6 look and feel...)
它在 iOS7 上看起来是这样的(iOS6 有 iOS6 的外观和感觉......)
回答by Ashwini Chougale
Objective C
目标 C
For iOS 10
we need integrate willPresentNotification
method for show notification banner in foreground
.
因为iOS 10
我们需要willPresentNotification
在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);
}
回答by Daniel Martín
If the application is running in the foreground, iOS won't show a notification banner/alert. That's by design. You have to write some code to deal with the situation of your app receiving a notification while it is in the foreground. You should show the notification in the most appropriate way (for example, adding a badge number to a UITabBar
icon, simulating a Notification Center banner, etc.).
如果应用程序在前台运行,iOS 将不会显示通知横幅/警报。那是设计使然。您必须编写一些代码来处理您的应用程序在前台时收到通知的情况。您应该以最合适的方式显示通知(例如,向UITabBar
图标添加徽章编号、模拟通知中心横幅等)。
回答by Prashant Gaikwad
Xcode 10 Swift 4.2
Xcode 10 斯威夫特 4.2
To show Push Notification when your app is in the foreground -
当您的应用程序在前台时显示推送通知 -
Step 1 :add delegate UNUserNotificationCenterDelegate in AppDelegate class.
第 1 步:在 AppDelegate 类中添加委托 UNUserNotificationCenterDelegate。
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
Step 2 :Set the UNUserNotificationCenter delegate
第 2 步:设置 UNUserNotificationCenter 委托
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
Step 3 :This step will allow your app to show Push Notification even when your app is in foreground
第 3 步:此步骤将允许您的应用程序即使在您的应用程序处于前台时也能显示推送通知
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
Step 4 :This step is optional. Check if your app is in the foreground and if it is in foreground then show Local PushNotification.
第 4 步:这一步是可选的。检查您的应用程序是否在前台,如果在前台,则显示本地推送通知。
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {
let state : UIApplicationState = application.applicationState
if (state == .inactive || state == .background) {
// go to screen relevant to Notification content
print("background")
} else {
// App is in UIApplicationStateActive (running in foreground)
print("foreground")
showLocalNotification()
}
}
Local Notification function -
本地通知功能 -
fileprivate func showLocalNotification() {
//creating the notification content
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = "App Update"
//content.subtitle = "local notification"
content.body = "New version of app update is available."
//content.badge = 1
content.sound = UNNotificationSound.default()
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
notificationCenter.add(request, withCompletionHandler: nil)
}
回答by SPatel
According to apple documentation, Yes you can display notification while app is running
根据苹果文档,是的,您可以在应用程序运行时显示通知
回答by marshy101
You can create your own notification that mimics the banner alert.
您可以创建自己的模仿横幅警报的通知。
One way is to create a custom uiview that looks like the banner and can animate and respond to touches. With this in mind you can create even better banners with even more functionality.
一种方法是创建一个自定义的 uiview,它看起来像横幅,并且可以为触摸设置动画和响应。考虑到这一点,您可以创建具有更多功能的更好的横幅。
Or you can look for an api that does it for you and add them as podfiles to your project.
或者,您可以查找为您执行此操作的 api,并将它们作为 podfile 添加到您的项目中。
Here are a couple that I have used:
这是我使用过的几个:
https://github.com/terryworona/TWMessageBarManager
https://github.com/terryworona/TWMessageBarManager
回答by Kavin Kumar Arumugam
Here is the code to receive Push Notification when app in active state (foreground or open). UNUserNotificationCenter documentation
这是当应用程序处于活动状态(前台或打开)时接收推送通知的代码。 UNUserNotificationCenter 文档
@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