在iOS前台应用程序时获取推送通知

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

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo

正在被调用,但通知屏幕中未显示通知。

我想在通知屏幕上显示通知,无论应用程序是在后台还是前台。我厌倦了寻找解决方案。任何帮助是极大的赞赏。

stack overflow Get push notification while App in foreground iOS
原文答案
author avatar

接受的答案

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

  • 检查应用程序是否在接收到远程时处于活动状态
    通知。如果处于活动状态,则触发 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 10,斯威夫特 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,斯威夫特 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])
}

您还必须将您的应用代理注册为通知中心的代理:

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
      ...
   }
作者头像

下面的代码将为您工作:

- (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];          
    }    
}
作者头像

对于任何可能感兴趣的人,我最终创建了一个自定义视图,该视图看起来像顶部的系统推送横幅,但添加了一个关闭按钮(蓝色小 X)和一个用于点击消息以进行自定义操作的选项。它还支持在用户有时间阅读/关闭旧通知之前到达多个通知的情况(不限制可以堆积多少......)

Link to GitHub: AGPushNote

用法基本在线:

[AGPushNoteView showWithNotificationMessage:@"John Doe sent you a message!"];

它在 iOS7 上看起来像这样(iOS6 具有 iOS6 的外观......)

enter image description here

作者头像

目标 C

enter image description here

对于 iOS 10 ,我们需要集成 willPresentNotification 方法以在 foreground 中显示通知横幅。

如果应用程序处于前台模式(活动)

- (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);
}
作者头像

Xcode 10 斯威夫特 4.2

当您的应用程序处于前台时显示推送通知 -

第 1 步: 在 AppDelegate 类中添加委托 UNUserNotificationCenterDelegate。

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

第 2 步: 设置 UNUserNotificationCenter 委托

let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self

第 3 步: 这一步将允许您的应用在前台显示推送通知

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])

    }

第 4 步:此​​步骤是可选的。检查您的应用程序是否在前台,如果它在前台,则显示 Local PushNotification。

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()
        }
    }

本地通知功能 -

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)
    }
作者头像

对于 Swift 5

1) 使用 UNUserNotificationCenterDelegate 向 AppDelegate 确认委托

2) UNUserNotificationCenter.current().delegate = self 中的 didFinishLaunch

3) 在 AppDelegate 中实现下面的方法。

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
     print("Push notification received in foreground.")
     completionHandler([.alert, .sound, .badge])
}

而已!

作者头像

如果应用程序在前台运行,iOS 将不会显示通知横幅/警报。这是设计使然。您必须编写一些代码来处理您的应用程序在前台接收通知的情况。您应该以最合适的方式显示通知(例如,将徽章编号添加到 UITabBar 图标、模拟通知中心横幅等)。

作者头像

您可以创建自己的模仿横幅警报的通知。

一种方法是创建一个看起来像横幅的自定义 uiview,并且可以动画和响应触摸。考虑到这一点,您可以创建具有更多功能的更好的横幅。

或者你可以寻找一个 api 为你做这件事,并将它们作为 podfiles 添加到你的项目中。

这是我用过的一对:

https://github.com/terryworona/TWMessageBarManager

https://github.com/toursprung/TSMessages

作者头像

这是当应用程序处于活动状态(前台或打开)时接收推送通知的代码。 UNUserNotificationCenter documentation

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

如果需要访问通知的userInfo 使用代码: notification.request.content.userInfo