0

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?

David Ensminger
  • 131
  • 1
  • 6
  • Why isn't `NavigationService.Navigate` async-await friendly? You would just have to display a default "loading" view before the await, then display either the login or the main view after. – McGarnagle Oct 14 '14 at 17:29
  • I'm not understanding. So are you saying I can `await NavigationSerivce.Navigate(...);` and then get the result of the authentication somehow afterwards? I'm not sure how I would do that. – David Ensminger Oct 14 '14 at 17:39

1 Answers1

1

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.

Community
  • 1
  • 1
David Ensminger
  • 131
  • 1
  • 6