You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何访问AnyHashable("aps")下alert键对应的值?

How to Extract Alert Text from Notification UserInfo in Swift

Hey there! I see you're trying to pull the alert message from your push notification payload—let's break this down step by step since you're still getting started with Swift.

The issue here is that the userInfo dictionary uses AnyHashable keys and stores values as Any, so we need to safely unwrap and cast each layer to get to the alert string. Here's how to do it:

Step-by-Step Fix

  1. First, extract the aps dictionary from userInfo (we cast it to [String: Any] because we know it's a key-value structure).
  2. Then, pull the alert value from that aps dictionary and cast it to a String—that's your target content.

Here's the updated version of your function with this logic added:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }
    
    // New code to extract alert text
    if let aps = userInfo["aps"] as? [String: Any] {
        if let alertText = aps["alert"] as? String {
            print("Alert content: \(alertText)")
            // Store alertText here for your后续 operations (like saving to a variable or using it in your UI)
        }
    }
    
    print(userInfo)
    completionHandler([.sound, .alert])
}

Why This Works

  • We use if let for safe optional unwrapping—this prevents crashes if the aps key doesn't exist or if the alert value isn't a string (super important for handling unexpected notification payloads!).
  • Even though the key shows up as AnyHashable("aps") in your print output, you can just use the string "aps" to access it—Swift automatically handles the AnyHashable matching under the hood.

Once you have alertText, you can store it in a property, display it in your app's UI, or use it for whatever logic you need next.

内容的提问来源于stack exchange,提问作者Kiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:40:45