应用在前台 iOS 时获取推送通知 [英] Get push notification while App in foreground iOS

查看:33
本文介绍了应用在前台 iOS 时获取推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用推送通知服务.当应用程序在后台时,我可以在通知屏幕上看到通知(当我们从 iOS 设备顶部向下滑动时显示的屏幕).但是如果应用程序在前台,则委托方法

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

- (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.

推荐答案

如果应用程序在前台运行,iOS 将不会显示通知横幅/警报.那是设计使然.但是我们可以通过使用UILocalNotification来实现,如下

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

  • 检查应用程序在接收远程时是否处于活动状态
    通知.如果处于活动状态,则触发 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];
}

斯威夫特:

if application.applicationState == .active {
    var localNotification = UILocalNotification()
    localNotification.userInfo = userInfo
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.alertBody = message
    localNotification.fireDate = Date()
    UIApplication.shared.scheduleLocalNotification(localNotification)
}

这篇关于应用在前台 iOS 时获取推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆