无法为UNMutableNotificationContent设置UserInfo的问题求助
如何正确设置UNMutableNotificationContent的UserInfo属性?
问题场景
尝试创建包含自定义数据的位置通知,计划用UserInfo字典存储自定义数据,但设置该属性时触发崩溃。
出错代码
var content = new UNMutableNotificationContent(); if (!string.IsNullOrWhiteSpace(value: notification.SoundFile)) { content.Sound = UNNotificationSound.GetCriticalSound(notification.SoundFile); } if (!string.IsNullOrEmpty(notification.ChannelDescription)) { content.ThreadIdentifier = notification.ChannelDescription; } content.Title = notification.Title; content.Body = notification.Text; content.CategoryIdentifier = "scheduled-alert"; // 崩溃发生在这一行 content.UserInfo = NSDictionary.FromObjectAndKey(new NSString("remainingTime"), new NSNumber((float)notification.Progress / 100f));
异常信息
System.NotSupportedException StackTrace " at Foundation.NSDictionary.set_Item (System.String key, Foundation.NSObject value) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/16.2.0.6/src/Xamarin.iOS/Foundation/NSDictionary.cs:376 \n at …"
问题原因与解决方法
崩溃的核心原因是NSDictionary.FromObjectAndKey的参数顺序搞反了——该方法的第一个参数是值,第二个参数是键,你当前的写法把键和值的位置颠倒,导致内部字典操作触发不支持的异常。
以下是几种正确的实现方式:
方法一:修正FromObjectAndKey的参数顺序
直接交换键值参数的位置即可:
// 第一个参数是值,第二个是键,修正顺序后赋值 content.UserInfo = NSDictionary.FromObjectAndKey(new NSNumber((float)notification.Progress / 100f), new NSString("remainingTime"));
方法二:使用FromObjectsAndKeys(适合扩展多键值对)
如果后续需要添加更多自定义数据,这种写法更便于扩展:
var keys = new NSObject[] { new NSString("remainingTime") }; var values = new NSObject[] { new NSNumber((float)notification.Progress / 100f) }; content.UserInfo = NSDictionary.FromObjectsAndKeys(values, keys);
方法三:使用NSMutableDictionary(灵活性更高)
用可变字典逐步添加键值对,写法更直观:
var userInfo = new NSMutableDictionary(); userInfo["remainingTime"] = new NSNumber((float)notification.Progress / 100f); content.UserInfo = userInfo;
采用以上任意一种写法,都能正常设置UserInfo属性,不会再触发崩溃。
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

