Xamarin.iOS, convert Dictionary to NSDictionary

后端 未结 2 1296
梦如初夏
梦如初夏 2021-02-20 07:42

Am trying to integrate Branch.io in my Xamarin project and came across this requirement to convert c#\'s Dictionary to NSDictionary.

Tried

  • dictionary as N
2条回答
  •  爱一瞬间的悲伤
    2021-02-20 08:11

    This is working for me .. could be optimized ofcourse or be much smarter :

    private static NSMutableDictionary ConvertToNativeDictionary(Dictionary dict)
    {
        NSMutableDictionary newDictionary = new NSMutableDictionary();
    
        try
        {
            foreach (string k in dict.Keys)
            {
                var value = dict[k];
    
                try
                {
                    if (value is string)
                        newDictionary.Add((NSString)k, new NSString((string)value));
                    else if (value is int)
                        newDictionary.Add((NSString)k, new NSNumber((int)value));
                    else if (value is float)
                        newDictionary.Add((NSString)k, new NSNumber((float)value));
                    else if (value is nfloat)
                        newDictionary.Add((NSString)k, new NSNumber((nfloat)value));
                    else if (value is double)
                        newDictionary.Add((NSString)k, new NSNumber((double)value));
                    else if (value is bool)
                        newDictionary.Add((NSString)k, new NSNumber((bool)value));
                    else if (value is DateTime)
                        newDictionary.Add((NSString)k, ((DateTime)value).DateTimeToNSDate());
                    else
                        newDictionary.Add((NSString)k, new NSString(value.ToString()));
                }
                catch (Exception Ex)
                {
                    if (value != null)
                        Ex.Data.Add("value", value);
    
                    Logger.LogException(Ex);
                    continue;
                }
            }
        }
        catch (Exception Ex)
        {
            Logger.LogException(Ex);
        }
        return newDictionary;
    }
    

    And this is NSDate Conversion :

    public static class NSDateExtensions
    {
        public static DateTime NSDateToDateTime(this NSDate date)
        {
            DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime(
                new DateTime(2001, 1, 1, 0, 0, 0));
            return reference.AddSeconds(date.SecondsSinceReferenceDate);
        }
    
        public static NSDate DateTimeToNSDate(this DateTime date)
        {
            DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime(
                new DateTime(2001, 1, 1, 0, 0, 0));
            return NSDate.FromTimeIntervalSinceReferenceDate(
                (date - reference).TotalSeconds);
        }
    
    }
    

提交回复
热议问题