我为UWP编写应用程序
我有PCL,我在这里编写从OpenWeather下载json的方法
这是代码。
public class WeatherRepositoryForUWP
{
private string url = "http://api.openweathermap.org/data/2.5/weather?q=London&units=imperial&APPID=274c6def18f89eb1d9a444822d2574b5";
public async void DownloadWeather()
{
var json = await FetchAsync(url);
Debug.WriteLine(json.ToString());
}
public async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
//var stream = httpClient.GetStreamAsync(url).Result;
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
// Classes for parser
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int pressure { get; set; }
public int humidity { get; set; }
public double temp_min { get; set; }
public int temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public int deg { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class Sys
{
public int type { get; set; }
public int id { get; set; }
public double message { get; set; }
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string @base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
}
}
此外,我有GUI,用户将其写入城市,并在点击按钮时写入变量。
以下是此代码:
private void city_button_Click(object sender, RoutedEventArgs e)
{
string city_name;
city_name = city_text.Text;
Debug.WriteLine(city_name);
}
我需要从city_name获取值并将其传递给PCL中的类并写入字符串变量。
我怎么能这样做?
感谢您的帮助!
答案 0 :(得分:2)
为了能够检索自定义城市的天气信息,您需要通过以下方式更改WeatherRepositoryForUWP
课程:
public class WeatherRepositoryForUWP
{
private string urlFormat = "http://api.openweathermap.org/data/2.5/weather?q={0}&units=imperial&APPID=274c6def18f89eb1d9a444822d2574b5";
public async Task<string> DownloadWeather(string city)
{
return await FetchAsync(string.Format(urlFormat, city));
}
// Rest of class remains unchanged....
}
然后,在您的点击事件处理程序中,您必须执行以下操作:
private void city_button_Click(object sender, RoutedEventArgs e)
{
string city_name;
city_name = city_text.Text;
var weatherService = new WeatherRepositoryForUWP();
string weatherData = weatherService.DownloadWeather(city_name).Result;
}