我正在尝试做Windows Phone 8中标题所说的内容,以下是我如何处理它:
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Add("listofCurrency", await CurrencyHelpers.getJsonCurrency());
}
在CurrencyHelpers中:
public async static Task<Dictionary<string, double>> getJsonCurrency()
{
HttpClient client = new HttpClient();
string jsonResult = await client.GetStringAsync("http://openexchangerates.org/api/latest.json?app_id=xxxxxxx");
JSONCurrency jsonData = JsonConvert.DeserializeObject<JSONCurrency>(jsonResult);
Dictionary<string, double> currencyCollection = new Dictionary<string, double>();
currencyCollection = jsonData.Rates;
return currencyCollection;
}
当MainPage加载时,我立即从CurrencyHelpers调用另一个方法:
public static KeyValuePair<double, double> getStorageCurrencyPairRates(string firstCurrency, string secondCurrency)
{
var settings = IsolatedStorageSettings.ApplicationSettings;
double firstCurrencyRate = 1;
double secondCurrencyRate = 1;
Dictionary<string, double> currencyCollection = new Dictionary<string,double>();
//needs some code here to check if "listofCurrency" already has JSONData stored in it.
settings.TryGetValue<Dictionary<string,double>>("listofCurrency", out currencyCollection);
foreach (KeyValuePair<string, double> pair in currencyCollection)
{
if (pair.Key == firstCurrency)
{
firstCurrencyRate = pair.Value;
}
else if (pair.Key == secondCurrency)
{
secondCurrencyRate = pair.Value;
}
}
return new KeyValuePair<double, double>(firstCurrencyRate, secondCurrencyRate);
}
}
我的想法是,我想将我的JSON数据存储到存储中,然后在可用时立即检索它,任何想法?非常感谢帮助!
答案 0 :(得分:0)
你用await和async思考的方式是正确的,但你通过在页面加载时调用另一个方法来破坏它的概念。 Wilfred Wee所说的也是错误的。
正确的方法是在App.xamls.cs中声明一个事件处理程序,如下所示:
public event EventHandler<bool> SettingsReady;
然后将Application_Launching()方法更改为以下内容:
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Add("listofCurrency", await CurrencyHelpers.getJsonCurrency());
if (SettingsReady!= null)
SettingsReady(this, true);
}
现在在你的MainPage.xaml.cs(CONSTRUCTOR - NOT WHEN LOADED)中声明要在数据准备就绪时调用的回调函数:
// Constructor
public MainPage()
{
InitializeComponent();
// Call back functions
App.SettingsReady += App_SettingsReady;
}
void App_SettingsReady(object sender, bool e)
{
// Here call your function for further data processing
getStorageCurrencyPairRates();
}