iOS Swift 应用在前台时如何接收推送通知

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] 值。如何像后台通知一样接收它?


你想从通知对象中访问用户信息吗? - PlusInfosys
@iOS_devloper 是的,先生。 - Kavin Kumar Arumugam
我正在使用 "notification.request.content.userInfo" 来获取数据。你可以在上面的方法中打印出来。 - Amanpreet
您可以使用 notification.request.content.userInfo。 - PlusInfosys
@iOS_devloper 如果解决了这个问题,你应该将其作为答案加入(如果你有更多细节,也可以添加一些)。干杯! - AL.
@AL. 谢谢!已发布。 - PlusInfosys
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])
}

如何在iOS 8.0中编写此代码?@Kavin Kumar Arumugam - Dilip Tiwari
好的,它会在前台显示通知,对吗Kavin Kumar Arumugam? - Dilip Tiwari
我在iOS 10中收到了,但在iOS 8中没有收到。@Kavin Kumar Arumugam - Dilip Tiwari
我们可以在群聊中交流吗,@kavin kumar arumugam。 - Dilip Tiwari
现在有点忙,晚上再看并更新你的代码 @DilipTiwari - Kavin Kumar Arumugam
显示剩余4条评论

1

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

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

}

1
UNNOtification有一个属性request(UNNotificationRequest),您可以使用它来获取用户信息。
使用以下方法从UNNotification访问用户信息:
let userinfo =  notification.request.content.userInfo

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接