[英]c# iOS 10 Notifications - GetDictionaryOfValuesFromKeys() error
对于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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.