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

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

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

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


当前回答

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

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

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

其他回答

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]

}

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

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

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

用于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
    }
}