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

标签 iphone ios objective-c push-notification

我在我的应用程序中使用推送通知服务。当应用程序在后台时,我可以在通知屏幕上看到通知(当我们从 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
      ...
   }

关于iphone - 在iOS前台应用程序时获取推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14872088/

相关文章:

iphone - 在 iPhone 应用程序中使用图形硬件进行音频处理

iphone - 重新分配变量时是否存在内存泄漏?

ios - VLCMobileKit iOS 在 iPhone 4 屏幕锁定时崩溃

objective-c - Objective-C 弧 : How to remove an object from an array/set and then return it as an autoreleased object?

iphone - Ios MFMailComposeViewController 不显示

iphone - 我应该使用哪个 iPhone API 来传输音频?

java - iOS 构建多个问题。

ios - 如何使用 swift 执行SelectorOnMainThread 并在不使用闭包的情况下获取返回值?

ios - 代码中具有自动布局约束的 iOS UITableView 中的可变单元格高度

ios - 使用 GooglePlus 类从 NSDictionary 获取键值