Ooui-tws-port/Samples/WeatherApp/Core.cs

68 lines
2.2 KiB
C#
Raw Normal View History

2017-12-12 20:43:38 +00:00
using System;
using System.Threading.Tasks;
namespace WeatherApp
{
public class Core
{
2018-06-29 15:30:18 +00:00
public static async Task<Weather> GetWeather(string zipCode, string units = "kelvin")
2017-12-12 20:43:38 +00:00
{
//Sign up for a free API key at http://openweathermap.org/appid
string key = "fc9f6c524fc093759cd28d41fda89a1b";
string queryString = "http://api.openweathermap.org/data/2.5/weather?zip="
2018-06-29 15:30:18 +00:00
+ zipCode + "&appid=" + key + "&units=" + units;
2017-12-12 20:43:38 +00:00
var results = await DataService.getDataFromService(queryString).ConfigureAwait(false);
if (results["weather"] != null)
{
2018-09-02 14:29:53 +00:00
string tempUnit = GetTempUnit(units);
string speedUnit = GetSpeedUnit(units);
2017-12-12 20:43:38 +00:00
Weather weather = new Weather
{
Title = (string)results["name"],
2018-09-02 14:29:53 +00:00
Temperature = (string)results["main"]["temp"] + tempUnit,
Wind = (string)results["wind"]["speed"] + speedUnit,
2017-12-12 20:43:38 +00:00
Humidity = (string)results["main"]["humidity"] + " %",
Visibility = (string)results["weather"][0]["main"]
};
DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DateTime sunrise = time.AddSeconds((double)results["sys"]["sunrise"]);
DateTime sunset = time.AddSeconds((double)results["sys"]["sunset"]);
weather.Sunrise = sunrise.ToString() + " UTC";
weather.Sunset = sunset.ToString() + " UTC";
return weather;
}
else
{
return null;
}
}
2018-09-02 14:29:53 +00:00
private static string GetSpeedUnit(string units)
{
switch (units)
{
case "imperial":
return " mph";
default:
return " kph";
}
}
private static string GetTempUnit(string units)
{
switch (units)
{
case "metric":
return " °C";
case "imperial":
return " °F";
default:
return " °K";
}
}
2017-12-12 20:43:38 +00:00
}
}