using System; using Shared.IOS.JLCountryCode; using Foundation; using System.Collections.Generic; using Newtonsoft.Json.Linq; using System.Net.Http; using System.Threading.Tasks; namespace JLCountrycode { public class CountryCodeView { /// /// /// private static CountryCodeView m_Current = null; /// /// /// public static CountryCodeView Current { get { if (m_Current == null) { m_Current = new CountryCodeView(); } return m_Current; } } /// /// 国家区号选择 /// /// public void Show(Action action) { JLCountryCodeController mJLCountryCodeController = new JLCountryCodeController(); mJLCountryCodeController.SelectCountryCodeBlock += (countryName, code) => { action?.Invoke(countryName, code); }; Shared.Application.currentVC.NavigationController.PushViewController(mJLCountryCodeController, true); } /// /// 选择 /// /// /// /// public void ShowSortSelection(string titleStr, Dictionary> dic, Action action) { try { JLSortSelectionViewController vc = new JLSortSelectionViewController(); vc.TitleStr = titleStr; vc.SortedNameDict = ConvertToNativeDictionary(dic); vc.SortSelectionBlock += (countryName) => { action?.Invoke(countryName); }; Shared.Application.currentVC.NavigationController.PushViewController(vc, true); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } /// /// Dictionary 转 iOS原生 NSMutableDictionary /// /// /// NSMutableDictionary ConvertToNativeDictionary(Dictionary> dict) { NSMutableDictionary newDictionary = new NSMutableDictionary(); try { //var dictDataList = new NSMutableArray(); foreach (string key in dict.Keys) { var value = dict[key]; newDictionary.Add(new NSString(key), NSArray.FromObjects(value.ToArray())); } } catch (Exception Ex) { Console.WriteLine(Ex.ToString()); } return newDictionary; } /// /// 根据手机当前的IP获取国家信息 /// /// public async Task GetCountryByIP() { string country = "Unknown"; try { using (HttpClient client = new HttpClient()) { // 使用 ipinfo.io 获取位置信息 HttpResponseMessage response = await client.GetAsync("https://ipinfo.io/json"); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); JObject jsonObject = JObject.Parse(json); // 从返回的 JSON 中提取国家信息 country = jsonObject["country"].ToString(); } } } catch (Exception ex) { Console.WriteLine($"Error fetching IP info: {ex.Message}"); } return country; } } }