【问题标题】:swift ios how to access AnyHashable data in swiftswift ios如何快速访问AnyHashable数据
【发布时间】:2018-04-12 05:53:52
【问题描述】:

如何快速访问任何 AnyHashable 数据我在下面有我的数据,下面是我单击通知时的日志。当我单击通知时,当我想打印或获取数据日志时,我可以将其加载到视图中。它已经在工作,当我点击通知时它会记录下来,如果我想要的是如何让它加载到视图中。

我做了什么

 guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSDictionary,
            let body = alert["body"] as? String,
            let title = alert["title"] as? String
            else {
                return
        }

        print("Title: \(title) \nBody:\(body)")

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

数据

[AnyHashable("aps"): {
    alert =     {
        body = "yuuu - 5.00";
        title = "New Chore!";
    };
    "content-available" = 1;
}, AnyHashable("data"): {
    chore =     {
        desc = huu;
        name = yuuu;
        pk = 125;
        reward = "5.00";
        sched = "2018-04-12T09:52:13+08:00";
    };
    "notification_id" = 16;
    pusher =     {
        publishId = "pubid-01ff965a-20af-4a58-9901-89782043d832";
    };
}]

【问题讨论】:

  • 您可能正在处理[AnyHashable:Any] 的字典,但在这种情况下,您的键似乎是String,因此您应该能够通过notif["alert"] 访问这些元素,例如
  • 你可以试试,让strTitle = (userInfo["aps"] as!NSDictionary).value(forKey: "notification") as! NSDictionary let title = strTitle.value(forKeyPath: "alert.title") let body = strTitle.value(forKeyPath: "alert.body")
  • 如果我没记错你想提取收到的通知数据对吗?
  • 请将其发布为答案先生,以便可以投票。谢谢
  • @AbhirajsinhThakore,没错

标签: ios swift hash


【解决方案1】:

你可以试试:

Swift 5+ 更新:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    guard let arrAPS = userInfo["aps"] as? [String: Any] else { return }
    if application.applicationState == .active{
        guard let arrAlert = arrAPS["alert"] as? [String:Any] else { return }

        let strTitle:String = arrAlert["title"] as? String ?? ""
        let strBody:String = arrAlert["body"] as? String ?? ""

        let alert = UIAlertController(title: strTitle, message: strBody, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default) { action in
            print("OK Action")
        })
        self.window?.rootViewController?.present(alert, animated: true)
    } else {
        guard let arrNotification = arrAPS["notification"] as? [String:Any] else { return }
        guard let arrAlert = arrNotification["alert"] as? [String:Any] else { return }

        let strTitle:String = arrAlert["title"] as? String ?? ""
        print("Title --", strTitle)
        let strBody:String = arrAlert["body"] as? String ?? ""
        print("Body --", strBody)
    }
}

Swift 2+:

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

    guard let dictAPS = userInfo["aps"] as? NSDictionary else { return }

    if application.applicationState == .active{
        let title = dictAPS.value(forKeyPath: "alert.title")
        let body = dictAPS.value(forKeyPath: "alert.body")
        let alert = UIAlertController(title: "\(title!)", message: "\(String(describing: body))", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default) { action in
                   })
        self.window?.rootViewController?.present(alert, animated: true)
    }else{
        guard let dictNoti = dictAPS.value(forKey: "notification") as? NSDictionary else { return }
        let title = dictNoti.value(forKeyPath: "alert.title")
        print(title)
        let body = dictNoti.value(forKeyPath: "alert.body")
        print(body)
    }
}

【讨论】:

  • 你可以试试: let strData = (userInfo["data"] as!NSDictionary) let desc = strData.value(forKeyPath: "chore.desc") let name = strData.value(forKeyPath: "chore.name") let pk = strData.value(forKeyPath: "chore.pk") let reward = strData.value(forKeyPath: "chore.reward") let sched = strData.value(forKeyPath: "chore.sched" )
  • 但我只想在点击通知时触发它
  • 这个方法会被调用 On tap:, func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { //你处理事件的代码 }
  • 'userNotificationCenter(_:didReceive: 的重新声明无效
  • 做里面的事情,我猜这只有在点击通知时才会被调用。
【解决方案2】:

anwer : 关于如何在点击通知时加载通知数据

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo["gcmMessageIDKey"] {
            print("Message ID: \(messageID)")
        }
        switch response.actionIdentifier {
        case "action1":
            print("Action First Tapped")
        case "action2":
            print("Action Second Tapped")
        default:
            break
        }

        // Print full message.
        print(userInfo)
        Messaging.messaging().appDidReceiveMessage(userInfo)
        completionHandler()
    }

【讨论】:

    【解决方案3】:

    APS 数据可以如下检查。如果通知数据中没有特定键,您可以检查每个键,以避免应用程序崩溃并进行相应处理。

    if (userInfo["aps"] as? [String:Any]) != nil {
       if let data = userInfo["data"] as? String{
          if let desc = userInfo["desc"] as? String {
              //Access variable desc here...
              print(desc)
          } 
       }
    }
    

    【讨论】:

    • 但如何仅在用户点击通知时触发它
    • 当应用程序处于后台或关闭时,当用户点击通知时将调用以下方法 - application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) 如果 App 在前台,您可以通过 UserNotificationCenter 方法和委托管理通知。
    • 我只想在点击通知时获取和打印数据
    • 好的。当应用程序在后台或从推送通知启动时,您将在“didReceiveRemoteNotification”方法中获取数据,如果您没有使用“UserNotificationCenter”管理应用程序,则不会显示应用程序正在运行的通知。在后面的情况下,您将在“userNotificationCenter didReceive response: UNNotificationResponse”方法中获得通知数据。使用上面的代码来处理它
    • 只有在点击通知时才会调用上述方法。
    猜你喜欢
    • 2022-10-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多