Friday, September 30, 2022

WebAuthenticationSession "The UIWindowScene for the returned window was not in the foreground active state."

In my case, I got this error (from a certain point of time if remember well), when implementing an OAuth protected API access upon a screen opens.

My platform is Xamarin.Forms.

Originally, I was doing so in the OnAppearing event handler. Opening WebAuthenticator browser etc. that sort of things. But at one point, on iOS, it stopped working, giving the following exception:

Error Domain=org.openid.appauth.general Code=-3 "(null)" UserInfo={NSUnderlyingError=0x60000299a7f0 {Error Domain=com.apple.AuthenticationServices.WebAuthenticationSession Code=3 "The UIWindowScene for the returned window was not in the foreground active state." UserInfo={NSDebugDescription=The UIWindowScene for the returned window was not in the foreground active state.}}}

It appears that the WebAuthentication browser can only be shown and return thereafter, to a foreground active window.

OK. Let us move it to another event handler which is called when the windows appeared, rather than appearing.

There seems, however, no such an event available in Xamarin.Forms, in the PCL project.

On the other hand, the iOS native UIViewController has the event ViewDidAppear, and we can code the handler through the PageRenderer.

I am still a newbie in Xamarin development, was not sure if such is possible. But wow! It works like a magic! I moved the API calling code from the page code behind class OnAppearing method to the PageRenderer. Only for iOS. For Android, it remains in the code behind class.

So the "life cycle" is, on iOS, the ViewDidAppear method is called first since there is a custom renderer is implemented, while on Android, simply only the OnAppearing method is called.