wxr
2024-09-27 acc8caee31c4be90bd38d1af18136b0e84f6fe94
HDL-ON_iOS/Other/JLCountrycode.cs
@@ -2,6 +2,9 @@
using Shared.IOS.JLCountryCode;
using Foundation;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace JLCountrycode
{
@@ -95,6 +98,39 @@
            return newDictionary;
        }
        /// <summary>
        /// 根据手机当前的IP获取国家信息
        /// </summary>
        /// <returns></returns>
        public async Task<string> 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;
        }
    }