I'm writing a Windows Phone 8 app that makes use of a REST API to gather data. The API requires authentication, so whenever I try to call the REST API, I have to check whether the user is authenticated. If the user isn't authenticated, then I want to bring up a login view and let the user authenticate. It's not HTTP authentication, but it uses a custom login screen.
My problem is: I would like to use await
to wait for the authentication to happen, but I don't know how to do that since I have to bring up another view. Here's pseudo-code for what I would like to do:
The LoadData method:
async Task LoadDataAsync() {
bool authenticated = await AuthenticateAsync();
if (authenticated) {
// do REST API stuff
}
}
And the AuthenticateAsync method:
async Task<bool> AuthenticateAsync() {
if (alreadyAuthenticated)
return true;
// not authenticated, so bring up a login view to let the user log in
// How do I do this in the context of async-await?
}
So in the AuthenticateAsync method I would like to bring up a login view if the user needs to authenticate. But I can't call NavigationService.Navigate()
because that's not async-await friendly and I wouldn't be able to await anything.
What's the right way to do this?
I found an answer to this. I ended up using the answer here: https://stackoverflow.com/a/12858633/225560
Specifically, I used a TaskCompletionSource<bool>
object, which I could then await. I then navigated to the login view, and it called me back when login was successful. I then set the result of the TaskCompletionSource, which freed up my await and let the method continue. This ended up working almost like a delegate in objective-C, in that the Login view called a method back on the initial class when login completed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.