对于 iOS 9 和之前的版本,我正在创建一些通知数据和一些用户数据的字典,最后将该数据传递给 UILocalNotification
的 UserInfo
属性创建本地通知时。
在 ReceivedLocalNotification
覆盖中,在我可以处理收到的通知之前,我使用 notification.UserInfo.ContainsKey()
检查以确定它是哪种类型的通知,然后适本地处理它.
为了适应新的 iOS 10 更改,我通过将值传递给新的 UNMutableNotificationContent
的 UserInfo
属性来保存额外的数据。当我尝试在 iOS 10 中检索这些额外数据时,遇到了挑战。
我已经实现了一个 UNUserNotificationCenterDelegate
类并覆盖了 DidReceiveNotificationResponse
函数。在此函数中,我尝试使用 GetDictionaryOfValuesFromKeys()
函数访问额外数据,但应用程序每次遇到该行时都会崩溃。
下面是我的代码:
我传递给通知的额外数据
NSMutableDictionary userInfo = new NSMutableDictionary();
userInfo.Add((NSString)Constants.PushNotificationInfoKeys.NOTIFICATION_TYPE, (NSNumber)((int)Constants.PushNotificationTypes.DRUG_ALERT));
userInfo.Add((NSString)Constants.PushNotificationInfoKeys.NOTIFICATION_IDENTIFIER, (NSString)alert.Id);
//Pass this data to the function that creates a local notification
alarmService.CreateAlarm(alarmTime, string.Format(..., userInfo);
创建报警函数
public Result<UILocalNotification> CreateAlarm(DateTime alertTime, string alertBody, string alertAction, NSMutableDictionary userInfo)
{
try
{
//Code truncated for clarity
// create the notification
var notification = new UILocalNotification();
//Set the metadata for the alert
notification.UserInfo = userInfo;
// schedule it
UIApplication.SharedApplication.ScheduleLocalNotification(notification);
return Result<UILocalNotification>.Success(notification);
}
catch (Exception ex)
{
return Result<UILocalNotification>.Failure(ex.Message);
}
}
我如何在 ReceivedLocalNotification
中检索数据
if (notification.UserInfo.ContainsKey(new NSString(Constants.PushNotificationInfoKeys.IS_RESPONSE_TO_SNOOZE)))
{
// Do something here
}
如何在 iOS 10 中检索数据:
public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
try
{
NSString[] keys = { new NSString(Constants.PushNotificationInfoKeys.NOTIFICATION_TYPE) };
var mystring = new NSString(Constants.PushNotificationInfoKeys.NOTIFICATION_TYPE);
var alertId = response.Notification.GetDictionaryOfValuesFromKeys(keys).ValueForKey(mystring); //App crashes on this line
}catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
}
}
如何访问 iOS 10 中的 UserInfo
属性?有任何想法吗?
谢谢。
最佳答案
经过一些研究,我了解到您可以从 DidReceiveNotificationResponse
函数内的响应对象访问 UserInfo 属性,如下所示:
var userInfo = response.Notification.Request.Content.UserInfo;
if (userInfo != null)
{
var value = userInfo.ValueForKey(mystring);
if (userInfo.ContainsKey(new NSString(Constants.PushNotificationInfoKeys. NOTIFICATION_TYPE)))
{
//Do something here
}
Console.WriteLine("Value :" + value);
}
关于c# iOS 10 通知 - GetDictionaryOfValuesFromKeys() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42228622/