private async Task ExecuteGetWeatherCommand() { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = IsImperial ? Units.Imperial : Units.Metric; if (UseGPS) { var gps = await CrossGeolocator.Current.GetPositionAsync(10000); weatherRoot = await WeatherService.GetWeather(gps.Latitude, gps.Longitude, units); } else { //Get weather by city weatherRoot = await WeatherService.GetWeather(Location.Trim(), units); } //Get forecast based on cityId Forecast = await WeatherService.GetForecast(weatherRoot.CityId, units); var unit = IsImperial ? "F" : "C"; Temp = $"Temp: {weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; // Set thermometer var tempValue = (float)weatherRoot?.MainWeather?.Temperature; if (tempValue > 0) { if (IsImperial) { PercentageTemperature = tempValue / 100f; } else { PercentageTemperature = tempValue / 30f; } } Condition = $"{weatherRoot.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; CrossTextToSpeech.Current.Speak(Temp + " " + Condition); } catch (Exception ex) { Temp = "Unable to get Weather"; } finally { IsBusy = false; } }
private async Task ExecuteGetWeatherCommand() { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = Units.Metric; //Get weather by city weatherRoot = await WeatherService.GetWeather(Location.Trim(), units); //Get forecast based on cityId Forecast = await WeatherService.GetForecast(weatherRoot.CityId, units); var unit = "C"; Temp = $"Temp: {weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; Condition = $"{weatherRoot.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; await TextToSpeech.SpeakAsync(Temp + " " + Condition); } catch (Exception ex) { Temp = "Nie można pobrać danych"; System.Diagnostics.Debug.WriteLine(ex.Message); } finally { IsBusy = false; } }
/// <summary> /// Selects the image. /// </summary> /// <returns>The image.</returns> /// <param name="weatherRoot">Weather root.</param> /// <param name="main">If set to <c>true</c> main.</param> string SelectImage(WeatherRoot weatherRoot, bool main = false) { var str = main ? "_white" : string.Empty; switch (weatherRoot.Weather[0]?.Description) { case "clear sky": return($"01{str}.png"); case "overcast clouds": return($"05{str}.png"); case "scattered clouds": case "broken clouds": case "few clouds": return($"04{str}.png"); case "moderate rain": case "heavy intensity rain": case "light intensity drizzle": return($"02{str}.png"); case "light rain": return($"06{str}.png"); case "moderate snow": case "heavy intensity snow": case "light snow": return($"07{str}.png"); default: return($"01{str}.png"); } }
public static WeatherPayload ToWeatherPayload(this WeatherRoot input) { var payload = new WeatherPayload { Forecasts = new List <DailyForecast>() }; foreach (var forecast in input.Forecasts) { payload.Forecasts.Add(new DailyForecast() { Day = new ForecastInformation() { Temperature = forecast.Day?.Temp ?? 0, Summary = forecast.Day?.Narrative, DayName = forecast.Day?.DayPartName }, Night = new ForecastInformation() { Temperature = forecast.Night.Temp, Summary = forecast.Night.Narrative, DayName = forecast.Night.DayPartName } }); } return(payload); }
public async Task GetWeatherAsync() { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = AppSettings.IsImperial ? Units.Imperial : Units.Metric; weatherRoot = await WeatherService.Instance.GetWeatherAsync(AppSettings.Location.Trim(), units); Forecast = await WeatherService.Instance.GetForecast(weatherRoot.CityId, units); var unit = AppSettings.IsImperial ? "F" : "C"; Temp = $"{weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; Condition = $"{weatherRoot.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; } catch (Exception ex) { Temp = "Unable to get Weather"; Debug.WriteLine(ex.Message); } finally { IsBusy = false; } }
private async void LoadWeather() { string codCity = SelectedCity.CODIGOINE.TrimEnd(new Char[] { '0' }); Weather = await ElTiempoAPI.GetWeather(SelectedCity.CODPROV, codCity); WeatherStateIcon = 'a' + Weather.stateSky.id; IsBusy = false; }
public static WeatherHistory ToHistory(this WeatherRoot weather) { return(new WeatherHistory { Icon = $"_{weather?.Weather?[0]?.Icon}.png", LocationDetails = $"{weather.Name} {weather.DisplayDate}", ShortenedWeather = $"Temp: {weather.DisplayTemp}, {weather.DisplayDescription}" }); }
//This class will be the one that connects to the api and provide Lockscreen with Weather information. public static async Task <WeatherRoot> GetWeather(string city, string country, string measurementunit) { string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0},{1}&units={2}&appid=9ca11a6f4426446b991ff390d4f7430f", city, country, measurementunit); using (var client = new HttpClient()) { try { var json = await client.GetStringAsync(url); if (string.IsNullOrWhiteSpace(json)) { return(null); } WeatherRoot weatherRoot = DeserializeObject <WeatherRoot>(json); configurationManager.SaveAValue(ConfigurationParameters.WeatherCity, weatherRoot.Name); configurationManager.SaveAValue(ConfigurationParameters.WeatherDescription, weatherRoot.Weather[0].Description); configurationManager.SaveAValue(ConfigurationParameters.WeatherHumidity, weatherRoot.MainWeather.Humidity.ToString() + "%"); configurationManager.SaveAValue(ConfigurationParameters.WeatherLastUpdated, DateTime.Now.ToString("ddd" + "," + "hh:mm")); configurationManager.SaveAValue(ConfigurationParameters.WeatherMaximum, weatherRoot.MainWeather.MaxTemperature.ToString()); configurationManager.SaveAValue(ConfigurationParameters.WeatherMaximum, weatherRoot.MainWeather.MinTemperature.ToString()); string temperatureSuffix = "--"; switch (measurementunit) { case "imperial": temperatureSuffix = "°f"; break; case "metric": temperatureSuffix = "°c"; break; } configurationManager.SaveAValue(ConfigurationParameters.WeatherCurrent, weatherRoot.MainWeather.Temperature.ToString() + temperatureSuffix); string unitsuffix = "°k"; switch (measurementunit) { case "imperial": unitsuffix = "°f"; break; case "metric": unitsuffix = "°c"; break; } configurationManager.SaveAValue(ConfigurationParameters.WeatherTemperatureUnit, unitsuffix); //?????? return(weatherRoot); } catch { return(null); } } }
public Task <WeatherForecastRoot> GetForecast(WeatherRoot weather, Units units = Units.Imperial) { if (weather.CityId == 0) { return(GetForecast(weather.Coordinates.Latitude, weather.Coordinates.Longitude, units)); } return(GetForecast(weather.CityId, units)); }
/// <summary> /// Populates todays weather. /// </summary> /// <param name="weatherRoot">Weather root.</param> void PopulateTodaysWeather(WeatherRoot weatherRoot) { var unit = IsImperial ? "F" : "C"; var temperature = (int)(weatherRoot?.MainWeather?.Temperature ?? 0); Temp = $"{temperature}°{unit}"; Condition = $"{weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; ConditionImage = SelectImage(weatherRoot, true); }
public async Task ExecuteGetWeatherCommand() { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = IsImperial ? Units.Imperial : Units.Metric; if (UseGPS) { //var gps = await CrossGeolocator.Current.GetPositionAsync(1000); //var gps = await Geolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10)); var gps = await Geolocation.GetLocationAsync(); weatherRoot = await WeatherService.GetWeather(gps.Latitude, gps.Longitude, units); } else { //Get weather by city weatherRoot = await WeatherService.GetWeather(Location.Trim(), units); } //await Task.Delay(500); //Get forecast based on cityId var fullForecast = await WeatherService.GetForecast(weatherRoot.CityId, units); Forecast.Clear(); foreach (var item in fullForecast.Items) { Forecast.Add(item); } var unit = IsImperial ? "F" : "C"; TempValue = weatherRoot?.MainWeather?.Temperature ?? 0; Humidity = weatherRoot?.MainWeather?.Humidity ?? 0; DisplayTemp = $"{weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; Condition = $"{weatherRoot.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; DisplayCity = weatherRoot?.Name; UpdateCalendar(); } catch (Exception ex) { DisplayTemp = "Unable to get Weather"; } finally { IsBusy = false; } }
/// <summary> /// 通过当前的菜品状态进行推荐。 /// </summary> /// <returns></returns> public async System.Threading.Tasks.Task <List <FoodInformation> > ReFlashAsync() { // 如果没录入了文件 if (foodInformationList == null) { userFavorInformationList = new List <FoodWeightChange>(); foodInformationList = await _loadJsonService.ReadJsonAsync(); userFavorInformationList = await _userFavorService.ReadJsonAsync(); //userChoiceList = await _userChoiceService.ReadJsonAsync(); InitWeight(foodInformationList, userFavorInformationList); } //获得食物的种数 //int len = foodInformationList.Capacity; if (weatherStatus == null) { WeatherRoot data = await _weatherService.GetWeatherAsync(); weatherStatus = new TempWeather(); weatherStatus.Temperature = double.Parse(data.main.temp).ToTemperature(); weatherStatus.Humidity = double.Parse(data.main.humidity).ToHumidity(); } //获取随机的食物 int changeWeightPosition = (3 * (int)weatherStatus.Temperature) + (int)weatherStatus.Humidity; List <Vector> foodVector = getFoodVector((int)weatherStatus.Temperature, (int)weatherStatus.Humidity); List <int> cos = GetCos(foodVector); int numberFoodToReturn = 5; int[] arr = new int[numberFoodToReturn]; // change int numOfGet = 0; while (numOfGet < numberFoodToReturn) { int getFoodNum = GetOneFoodNum(cos); //该食物已经获取 if (Array.IndexOf(arr, getFoodNum) != -1) { continue; } arr.SetValue(getFoodNum, numOfGet++); } List <FoodInformation> get_foodInformation = new List <FoodInformation>(); for (int i = 0; i < numberFoodToReturn; i++) { get_foodInformation.Add(foodInformationList[arr[i]]); } return(get_foodInformation); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); //Xamarin.Essentials.Platform.Init(this, savedInstanceState); //// Set our view from the "main" layout resource //SetContentView(Resource.Layout.activity_main); SetContentView(Resource.Layout.activity_main); msgText = FindViewById <TextView>(Resource.Id.msgText); weaText = FindViewById <TextView>(Resource.Id.weatherText); if (Intent.Extras != null) { foreach (var key in Intent.Extras.KeySet()) { var value = Intent.Extras.GetString(key); Log.Debug(TAG, "Key: {0} Value: {1}", key, value); } } IsPlayServicesAvailable(); CreateNotificationChannel(); // Get Token var logTokenButton = FindViewById <Button>(Resource.Id.logTokenButton); logTokenButton.Click += delegate { Log.Debug(TAG, "InstanceID token: " + FirebaseInstanceId.Instance.Token); }; // Topic message var subscribeButton = FindViewById <Button>(Resource.Id.subscribeButton); subscribeButton.Click += delegate { FirebaseMessaging.Instance.SubscribeToTopic("news"); Log.Debug(TAG, "Subscribed to remote notifications"); }; var getWeatherButton = FindViewById <Button>(Resource.Id.getWeatherButton); getWeatherButton.Click += async delegate { WeatherRoot weatherRoot = await GetWeather("Ha Noi"); if (weatherRoot != null) { weaText.Text = weatherRoot.DisplayIcon; } Log.Debug(TAG, SerializeObject(weatherRoot)); }; var sendFCMNotification = FindViewById <Button>(Resource.Id.sendFCMNotification); sendFCMNotification.Click += async delegate { weaText.Text = await SendFCM(FirebaseInstanceId.Instance.Token.ToString()); }; }
private CurrentWeatherData ProcessObject(WeatherRoot weather) { return(new CurrentWeatherData { City = weather.City, ImagePath = ProcessImagePath(weather.WeatherData[0].Weather.WeatherIcon), Temperature = weather.WeatherData[0].CurrentTemperature, Condition = weather.WeatherData[0].Weather.ConditionDescription, Updated = DateTime.Now.ToString("HH:mm") }); }
private static WeatherMessage CreateBlobTriggerMessage(LocationMessage messageParam, string content) { WeatherRoot weather = (WeatherRoot)JsonConvert.DeserializeObject(content, typeof(WeatherRoot)); WeatherMessage message = new WeatherMessage(weather) { CityName = messageParam.CityName, Blob = messageParam.Blob, Guid = messageParam.Guid, }; return(message); }
private async Task ExecuteGetWeatherCommand() { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = IsImperial ? Units.Imperial : Units.Metric; if (UseGPS) { var hasPermission = await CheckPermissions(); if (!hasPermission) { return; } var gps = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10)); weatherRoot = await WeatherService.GetWeather(gps.Latitude, gps.Longitude, units); } else { //Get weather by city weatherRoot = await WeatherService.GetWeather(Location.Trim(), units); } //Get forecast based on cityId Forecast = await WeatherService.GetForecast(weatherRoot.CityId, units); var unit = IsImperial ? "F" : "C"; Temp = $"Temp: {weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; Condition = $"{weatherRoot.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; CrossTextToSpeech.Current.Speak(Temp + " " + Condition); } catch (Exception ex) { Temp = "Unable to get Weather"; } finally { IsBusy = false; } }
public async Task <Position> GetCurrentPosition() { Position position = null; WeatherRoot weatherRoot = new WeatherRoot(); var units = Units.Imperial; try { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 100; position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true); weatherRoot = await GetWeather(position.Latitude, position.Longitude, Units.Imperial); Location = weatherRoot.Name; Temperature = weatherRoot.DisplayTemp; var rain = weatherRoot.MainWeather.Humidity; var weather = weatherRoot.Clouds; if (weather.CloudinessPercent < 20) { WeatherImageSource = "Sun_icon.png"; } else if (rain > 80) { WeatherImageSource = "Rain_icon"; } else { WeatherImageSource = "Clouds_icon.png"; } } catch (Exception ex) { Debug.WriteLine("Unable to get location: " + ex); } if (position == null) { return(null); } var output = string.Format("Time: {0} \nLat: {1} \nLong: {2} \nAltitude: {3} \nAltitude Accuracy: {4} \nAccuracy: {5} \nHeading: {6} \nSpeed: {7}", position.Timestamp, position.Latitude, position.Longitude, position.Altitude, position.AltitudeAccuracy, position.Accuracy, position.Heading, position.Speed); Debug.WriteLine(output); return(position); }
public async Task GetWeatherAsync() { if (IsBusy) { return; } IsBusy = true; try { var location = AppSettings.Location.Trim(); WeatherRoot weatherRoot = null; if (!CrossConnectivity.Current.IsConnected) { weatherRoot = Barrel.Current.Get <WeatherRoot>(key: location); Forecast = Barrel.Current.Get <WeatherForecastRoot>(key: weatherRoot.CityId.ToString()); } else if (!Barrel.Current.IsExpired(key: location)) { weatherRoot = Barrel.Current.Get <WeatherRoot>(key: location); Forecast = Barrel.Current.Get <WeatherForecastRoot>(key: weatherRoot.CityId.ToString()); } else { weatherRoot = await WeatherService.Instance.GetWeatherAsync(location); Barrel.Current.Add(key: location, data: weatherRoot, expireIn: TimeSpan.FromHours(1)); Forecast = await WeatherService.Instance.GetForecast(weatherRoot.CityId); Barrel.Current.Add(key: weatherRoot.CityId.ToString(), data: Forecast, expireIn: TimeSpan.FromHours(1)); } var unit = "C"; Temp = $"{weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; Condition = $"{weatherRoot.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; } catch (Exception ex) { Temp = "Unable to get Weather"; Debug.WriteLine(ex.Message); } finally { IsBusy = false; } }
private void DoWork(object state) { string msImgUrl = BC.WebBC.getBackgrndImgUrl(_appConfig.Value.msImageUrl); /*root.name - "Troy" * Weather[0].main - "Clouds". * Weather[0].description - scattered clouds * root.main.feels_like * "" "" temp * "" "" temp_max * "" "" temp_min*/ WeatherRoot wr = BC.WebBC.getWeatherData(_appConfig.Value.openWeatherUrl, _appConfig.Value.openWeatherKey); string r = ""; }
private static string GenerateBeerText(WeatherRoot weather) { string maintext = ""; if (weather.Main.Temp < 15) { maintext = "Brr het is een beetje te koud voor bier drink wat gore gluhwein ofzo"; } else { maintext = "Wat een lekker weer voor een biertje"; } return(maintext); }
public void AddHourlyForecastWeatherDataToUI(WeatherRoot weather, string typeOfData) { forecastHourly.Clear(); if (typeOfData == "randomized") { weather.WeatherData = RandomizeHourlyForecast(weather.WeatherData); } foreach (var item in FilterList(weather.WeatherData)) { forecastHourly.Add(ProcessObject(item)); forecastHourlyItemsControl.ItemsSource = forecastHourly; } }
public void Run(string townParm = null) { if (String.IsNullOrEmpty(_openWeatherMapKey)) { Console.WriteLine("Whoops! API key is not defined."); Console.WriteLine("Get an API key from https://home.openweathermap.org/api_keys then.."); Console.WriteLine("run dotnet user-secrets set \"SecretsModel: OpenWeatherMapApiKey\" \"12345\" to specify your key"); return; } Console.Write("Enter your town name:"); string town = (String.IsNullOrEmpty(townParm)) ? Console.ReadLine() : townParm; string resp = ""; WeatherRoot wr = new WeatherRoot(); try { using (var wc = GetWebClient()) { resp = wc.DownloadString($"http://api.openweathermap.org/data/2.5/weather?q={town}&appid={_openWeatherMapKey}"); } wr = JsonSerializer.Deserialize <WeatherRoot>(resp); } catch { Console.WriteLine("Got no result or couldn't convert to Weather object"); return; } Console.WriteLine(); Console.WriteLine("Temperature: " + Weather.KtoF(wr.Main.Temperature) + "°F or " + Weather.KtoC(wr.Main.Temperature) + "°C. Feels like: " + Weather.KtoF(wr.Main.Temperature) + "°F or " + Weather.KtoC(wr.Main.Temperature) + "°C"); Console.WriteLine("Wind speed: " + wr.Wind.Speed + " m/s. Air pressure is " + wr.Main.Pressure + "mmHg or " + Math.Round(wr.Main.Pressure * 133.322, 1) + " Pascals."); long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); bool SunWhat = currentTime > wr.Sys.Sunrise; long whatNext = SunWhat ? wr.Sys.Sunset : wr.Sys.Sunrise; long diff = whatNext - currentTime; var dto = DateTimeOffset.FromUnixTimeSeconds(diff); if (SunWhat) //If sun should be setting... { Console.WriteLine("It's day right now. The sun will set in " + dto.ToString("HH:mm:ss")); } else { Console.WriteLine("It's night right now. The sun will rise in " + dto.ToString("HH:mm:ss")); } }
async Task ExecuteGetWeatherCommand(bool useGps) { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = IsImperial ? Units.Imperial : Units.Metric; if (useGps) { var gps = await Geolocation.GetLocationAsync().ConfigureAwait(false); weatherRoot = await WeatherService.GetWeather(gps.Latitude, gps.Longitude, units).ConfigureAwait(false); } else { //Get weather by city weatherRoot = await WeatherService.GetWeather(Location.Trim(), units).ConfigureAwait(false); } //Get forecast based on cityId Forecast = await WeatherService.GetForecast(weatherRoot, units).ConfigureAwait(false); var unit = IsImperial ? "F" : "C"; Temperature = $"Temp: {weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; Condition = $"{weatherRoot.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; IsBusy = false; await TextToSpeech.SpeakAsync(Temperature + " " + Condition).ConfigureAwait(false); } catch (Exception e) { DebugServices.Report(e); Temperature = "Unable to get Weather"; } finally { IsBusy = false; } }
//测试天气获取 public async System.Threading.Tasks.Task Test4Async() { Location location = new Location(); location.Lat = 45; location.Lon = 45; var locationServiceMock = new Mock <ILocationService>(); locationServiceMock.Setup(w => w.GetLocationAsync()).ReturnsAsync(location); var mockLocationService = locationServiceMock.Object; IWeatherService weatherService = new WeatherService(mockLocationService); WeatherRoot data = await weatherService.GetWeatherAsync(); Assert.AreEqual("RU", data.sys.country); }
public static async Task <WeatherRoot> GetWeatherDataByCity(string city) { string url = new Constants().GetURLByCity(city); WeatherRoot weatherData = new WeatherRoot(); using (HttpClient client = new HttpClient()) { var response = await client.GetAsync(url); var json = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject <WeatherRoot>(json); } return(weatherData); }
private async Task ExecuteGetWeatherCommand() { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = IsImperial ? Units.Imperial : Units.Metric; if (UseGPS) { var gps = await CrossGeolocator.Current.GetPositionAsync(10000); weatherRoot = await WeatherService.GetWeather(gps.Latitude, gps.Longitude, units); } else { //Get weather by city weatherRoot = await WeatherService.GetWeather(Location.Trim(), units); } //Get forecast based on cityId Forecast = await WeatherService.GetForecast(weatherRoot.CityId, units); var unit = IsImperial ? "F" : "C"; Temp = $"Temp: {weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; Condition = $"{weatherRoot?.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; CrossTextToSpeech.Current.Speak(Temp + " " + Condition); } catch (Exception ex) { Temp = _errorMessage; HockeyappHelpers.Report(ex); } finally { IsBusy = false; TrackGetWeatherEvent(); } }
//ICommand getWeather; //public ICommand GetWeatherCommand => // getWeather ?? // (getWeather = new Command(async () => await ExecuteGetWeatherCommand())); public async Task ExecuteGetWeatherCommand() { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = IsImperial ? Units.Imperial : Units.Metric; if (UseGPS) { var gps = await CrossGeolocator.Current.GetPositionAsync(10000); weatherRoot = await WeatherService.GetWeather(gps.Latitude, gps.Longitude, units); } else { //Get weather by city weatherRoot = await WeatherService.GetWeather(Location.Trim(), units); } //Get forecast based on cityId Forecast = await WeatherService.GetForecast(weatherRoot.CityId, units); var unit = IsImperial ? "F" : "C"; var temp = (int)(weatherRoot?.MainWeather?.Temperature ?? 0); Temp = $"{temp}°{unit}"; Condition = $"{weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; //CrossTextToSpeech.Current.Speak(Temp + " " + Condition); } catch { Temp = "Unable to get Weather"; } finally { IsBusy = false; } }
/// <summary> /// 初始化信息 /// </summary> public async void InitRecommendationAsync() { userFavorInformationList = new List <FoodWeightChange>(); foodInformationList = await _loadJsonService.ReadJsonAsync(); _foodFavorService.InitAsync(foodInformationList); await _logService.InitAsync(); userFavorInformationList = await _userFavorService.ReadJsonAsync(); InitWeight(foodInformationList, userFavorInformationList); WeatherRoot data = await _weatherService.GetWeatherAsync(); weatherStatus = new TempWeather(); weatherStatus.Temperature = double.Parse(data.main.temp).ToTemperature(); weatherStatus.Humidity = double.Parse(data.main.humidity).ToHumidity(); }
public static string GetWeather(string location) { //gets the weather information of the location const string urlHead = "http://weerlive.nl/api/json-data-10min.php?key=3e65790d54&locatie="; string fullUrl = urlHead + location; using (WebClient httpClient = new WebClient()) { string jsonData = httpClient.DownloadString(fullUrl); WeatherRoot weatherRoot = JsonConvert.DeserializeObject <WeatherRoot>(jsonData); Weather weather = weatherRoot.WeatherArr[0]; //return the c# object names instead of the JsonProperty names SerializationHelper serializationHelper = new SerializationHelper(); string result = serializationHelper.Serialize(weather, true); return(result); } }
private async Task ExecuteGetWeatherCommand() { if (IsBusy) { return; } IsBusy = true; try { WeatherRoot weatherRoot = null; var units = IsImperial ? Units.Imperial : Units.Metric; if (UseGPS) { //Get weather by GPS var local = await CrossGeolocator.Current.GetPositionAsync(10000); weatherRoot = await WeatherService.GetWeather(local.Latitude, local.Longitude, units); } else { //Get weather by city weatherRoot = await WeatherService.GetWeather(Location.Trim(), units); } //Get forecast based on cityId Forecast = await WeatherService.GetForecast(weatherRoot.CityId, units); var unit = IsImperial ? "F" : "C"; Temp = $"Temp: {weatherRoot?.MainWeather?.Temperature ?? 0}°{unit}"; Condition = $"{weatherRoot.Name}: {weatherRoot?.Weather?[0]?.Description ?? string.Empty}"; } catch (Exception ex) { Temp = "Unable to get Weather"; Xamarin.Insights.Report(ex); } finally { IsBusy = false; } }