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
- First, extract the
apsdictionary fromuserInfo(we cast it to[String: Any]because we know it's a key-value structure). - Then, pull the
alertvalue from thatapsdictionary and cast it to aString—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 letfor safe optional unwrapping—this prevents crashes if theapskey doesn't exist or if thealertvalue 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 theAnyHashablematching 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
相关产品推荐
相关产品推荐

