5

这是我在前台应用程序时用来接收推送通知的代码

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
{
     completionHandler([UNNotificationPresentationOptions.Alert,UNNotificationPresentationOptions.Sound,UNNotificationPresentationOptions.Badge])
}

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

4

5 回答 5

8

在 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])
}
于 2017-04-21T06:55:35.923 回答
1
 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

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

}
于 2016-12-27T07:09:18.227 回答
1

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

于 2016-12-27T07:15:27.467 回答
1

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

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

let userinfo =  notification.request.content.userInfo
于 2016-12-28T07:41:03.887 回答
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)
 
}
于 2021-03-18T08:43:00.453 回答