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

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

正在被调用,但通知屏幕上没有显示通知。

我想在通知屏幕上显示通知,不管应用程序是在后台还是前台。我厌倦了寻找解决办法。任何帮助都非常感激。


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


正如@Danial Martine所说,iOS不会显示通知横幅/提醒。这是故意的。但如果真要这么做,还有一个办法。我也用同样的方法做到了这一点。

1.从parse FrameWork下载解析框架

2.导入# Import <Parse/Parse.h> .h

3.将以下代码添加到您的didReceiveRemoteNotification方法

 - (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [PFPush handlePush:userInfo];
}

PFPush会注意如何处理远程通知。如果App在前台,这显示警报,否则它显示在顶部的通知。


下面的代码将为您工作:

- (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];          
    }    
}

如果应用程序在前台运行,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]; }

迅速:

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

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

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

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

以下是我使用过的一些方法:

https://github.com/terryworona/TWMessageBarManager

https://github.com/toursprung/TSMessages


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

链接到GitHub: AGPushNote

用法基本上是在线的:

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

在iOS7上看起来是这样的(iOS6有一个iOS6的外观和感觉…)


如果你的应用程序处于前台状态,这意味着你正在使用同一个应用程序。所以通常没有必要在顶部显示通知。

但如果你想显示通知在那种情况下你必须创建你的自定义警报视图或自定义视图像Toast或其他东西来向用户显示你已经收到通知。

如果你的应用中有这样的功能,你也可以在顶部显示一个徽章。


当应用程序在前台显示横幅消息时,使用以下方法。

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:

@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
      ...
   }

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

@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


Objective - C

对于iOS 10,我们需要集成willPresentNotification方法来在前台显示通知横幅。

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

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

添加completionHandler行委托方法为我解决了同样的问题:

//Called when a notification is delivered to a foreground app.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

completionHandler([.alert, .badge, .sound])
} 

在你的应用委托中使用下面的代码

import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
 var currentToken: String?
 var window: UIWindow?
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        application.registerForRemoteNotifications()
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in

            // Enable or disable features based on authorization.
            if granted == true
            {
                print("Allow")
                UIApplication.shared.registerForRemoteNotifications()
            }
            else
            {
                print("Don't Allow")
            }
        }
        UNUserNotificationCenter.current().delegate = self

        return true
    }
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
        let token = tokenParts.joined()
        currentToken = token  //get device token to delegate variable

    }
 public class var shared: AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
         completionHandler([.alert, .badge, .sound])
    }
}

如上所述,您应该使用UserNotification.framework来实现这一点。但出于我的目的,我必须在app中显示它,我想要iOS 11风格,所以我创建了一个小助手视图,可能对某些人有用。

GitHub iOS 11推送通知视图。


Xcode 10 Swift 4.2

当你的应用程序在前台时,显示推送通知

步骤1:在AppDelegate类中添加delegate UNUserNotificationCenterDelegate。

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

步骤2:设置UNUserNotificationCenter委托

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

第三步:这一步将允许你的应用程序显示推送通知,即使你的应用程序在前台

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

    }

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

本地通知功能-

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解析推送通知字典

    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
            if application.applicationState == .active {
                if let aps1 = data["aps"] as? NSDictionary {
                    if let dict = aps1["alert"] as? NSDictionary {
                        if let strTitle = dict["title"] as? String , let strBody = dict["body"] as? String {
                            if let topVC = UIApplication.getTopViewController() {
                                //Apply your own logic as per requirement
                                print("strTitle ::\(strTitle) , strBody :: \(strBody)")
                            }
                        }
                    }
                }
            }
        }

获取topBanner所在的top viewController

extension UIApplication {

    class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return getTopViewController(base: nav.visibleViewController)

        } else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
            return getTopViewController(base: selected)

        } else if let presented = base?.presentedViewController {
            return getTopViewController(base: presented)
        }
        return base
    }
}

最好的方法是通过使用扩展AppDelegate: UNUserNotificationCenterDelegate在AppDelegate中添加UNUserNotificationCenterDelegate 该扩展告诉应用程序能够在使用时获得通知

并实现这个方法

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

只有当应用程序在前台时,才会在委托上调用此方法。

最后的实现:

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler(.alert)
    }
}

要调用这个,你必须在AppDelegate中在didFinishLaunchingWithOptions中设置委托添加这一行

UNUserNotificationCenter.current().delegate = self

你可以修改

completionHandler(.alert) 

completionHandler([.alert, .badge, .sound]))

Swift 5

1)使用UNUserNotificationCenterDelegate确认委托到AppDelegate 2)在didFinishLaunch中UNUserNotificationCenter.current().delegate = self 3)在AppDelegate中实现如下方法。

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

就是这样!


100%工作测试

第一次进口

import UserNotifications

然后在类中添加委托

UNUserNotificationCenterDelegate


class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate

下面的方法是负责,而应用程序是打开和通知来。

将呈现

   @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            let content = notification.request.content

           let alertVC = UIAlertController.init(title: title, message: body, preferredStyle: .alert)

            alertVC.addAction(UIAlertAction.init(title: appLan_share.Ok_txt, style: .default, handler: {
                _ in
                   //handle tap here or navigate somewhere…..                
            }))

            vc?.present(alertVC, animated: true, completion: nil)

            print("notification Data: \(content.userInfo.values)")
                completionHandler([.alert, .sound])



}

您还可以通过检查当前应用程序状态来处理应用程序状态。

此外,如果你的应用程序没有运行,那么下面的方法是负责处理推送通知

didReceive

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        let aps = userInfo["aps"] as? [String: Any]
        let alert = aps?["alert"] as? [String: String]

}

iOS 14 +

下面这个答案有一个不同之处,.alert已弃用,使用.banner:

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
    ) -> Bool {
        UNUserNotificationCenter.current().delegate = self

        return true
    }

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

也适用于iOS 14+,不需要手动处理任何警报或视图,只需让iOS做它的事情

在里面,我们重新收到通知替换如下代码

func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler:
    @escaping (UNNotificationPresentationOptions) -> Void
  ) {
    
    if (UIApplication.shared.applicationState == .inactive || UIApplication.shared.applicationState == .background) {
      if #available(iOS 14.0, *) {
        completionHandler([[.banner, .sound]])
      } else {
        completionHandler([.alert, .sound])
      }
    } else {
      if #available(iOS 14.0, *) {
        completionHandler([[.banner]])
      } else {
        completionHandler([.alert])
      }
    }
  }

要注意的主要事情是不要使用声音,而在前景,它不会显示横幅