异步调用Web API后,导航控制器不起作用。我尝试了几种不同的技术,但想法不多了。...
这是我使用的代码:
// LoginController:
LoginButton.TouchUpInside += (object sender, EventArgs e) =>
{
var user = Task.Run(() => await service.LoginAsync(EmailTextField.Text, PasswordTextField.Text));
user.Wait();
if (user.Success)
{
UserDefaults.SetString(user.UserId, "UserId");
UserDefaults.SetString(user.Username, "Email");
UserDefaults.SetString(user.Lastname, "Lastname");
UserDefaults.SetString(user.Firstname, "Firstname");
UserDefaults.SetString(user.Token, "Token");
UserDefaults.SetString(user.RefreshToken, "RefreshToken");
Nav.PushViewController(new HomeController(0), true);
}
else
{
...
}
};
// APIService.cs
public async Task<UserViewModel> LoginAsync(string username, string password)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
var model = new LoginViewModel()
{
Username = username,
Password = password
};
var json = JsonConvert.SerializeObject(model);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("url", content);
var result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var user = JsonConvert.DeserializeObject<UserViewModel>(result);
user.Username = username;
return user;
}
return JsonConvert.DeserializeObject<UserViewModel>(result);
}
}
你能帮我吗?
谢谢:)
您可以尝试这段代码,因为您的方法可能需要花一些时间才能执行
var user =Task.Run(() => await service.LoginAsync(EmailTextField.Text, PasswordTextField.Text)).Wait();
但是不建议使用void
方法async
。您可以使用void
代替Task
。
进行这样的按钮单击事件
LoginButton.TouchUpInside += async delegate
{
//code
};