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

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

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

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

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

最佳答案

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

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

https://stackoverflow.com/questions/14872088/

相关文章:

objective-c - ARC 和桥接铸件

objective-c - 什么时候应该在 Objective-C 中使用 nil 和 NULL?

objective-c - 在 View Controller 之间进行通信的最佳方式是什么?

ios - 如何将方法调用延迟 1 秒?

objective-c - Objective-C 可以打开 NSString 吗?

objective-c - 使用 block 在 `self` 上保留循环

ios - 从后台打开应用程序时不调用 ViewDidAppear

ios - 处理 NSDateFormatter 语言环境 "feature"的最佳方法是什么?

ios - UIImageView 方面适合和居中

ios - 如何将本地 html 文件加载到 UIWebView