当前景中的应用程序时,iOS Swift接收推送通知

时间:2016-12-27 07:01:32

标签: ios push firebase-notifications unusernotificationcenter

以下是我在前台应用

时用于接收推送通知的代码
@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
{
     completionHandler([UNNotificationPresentationOptions.Alert,UNNotificationPresentationOptions.Sound,UNNotificationPresentationOptions.Badge])
}

但我的问题是我的通知包含[NSObject:AnyObject]值。如何收到类似的背景通知

5 个答案:

答案 0 :(得分:6)

在AppDelegate.swift文件中添加此代码。

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

答案 1 :(得分:1)

 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

   if (application.applicationState == 0) // active --- forground
    {
       // publish your notification message
    }

}

答案 2 :(得分:1)

你的应用程序将无法运行任何代码,除非用户打开推送通知,推送通知由操作系统处理,并且您的应用程序在它不活动时无法控制它们或在后台你应该看看https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/OptimizeVoIP.html

答案 3 :(得分:1)

UNNOtification有财产请求(UNNotificationRequest),您可以使用它来获取用户信息。

使用以下命令从UNNotification访问用户信息:

let userinfo =  notification.request.content.userInfo

答案 4 :(得分:0)

  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
{
    debugPrint("Received when is visible... :): \(userInfo)")
    

    guard let aps = userInfo["aps"] as? [String: AnyObject] else {
        completionHandler(.failed)
        return
      }
    
    let alert:Dictionary<String,String> = aps["alert"] as! Dictionary<String,String>

    let title:String = alert["title"]!
    let msg:String   = alert["body"]!
    
  
    let refreshAlert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertController.Style.alert)
    
    refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
         
        refreshAlert.dismiss(animated: true, completion: nil)
      
    }))


    UIApplication.shared.windows.first!.rootViewController?.present(refreshAlert, animated: true, completion: nil)
 
}