I am building an app with Xamarin, using a PCL project, so I have my core functionality there, with platform specific implementations in different projects. I am using the MVVM structure, but with Xamarin I have complicated things. I am using Xamarin.Auth, which allows OAuth2 logins, but it is only available on the .ios and .droid projects.
So I have a “Log in with?” prompt on a view in the core project. Then I go to the platform specific project which calls a Custom Renderer (model shown here).
Here is the code in the renderer, which needs to be “customised” based on the authenticator selected by the user.
var auth = new OAuth2Authenticator (
clientId: "xxx", // your OAuth2 client id (For FB Also called App-ID)
scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"), // the auth URL for the service (i.e FB, Twitter)
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html")); // the redirect URL for the service
What is the correct way of doing this? Do I use public variables to communicate this, pass the details through? etc. What is the simplest solution?
2
Answers
Normally you would create an interface in PCL and then create classes in the platform-specific projects that implement it.
In your case, it might be something like this
AuthenticateResult should be a class that is also available in PCL.
Once you got that, you would just inject interface into your view models.
Note, that you have to register your interface implementation in a platform-specific project.
MVVMCross is a relatively good framework that might help you with what you are trying to achieve.
You must create a dependency class,that’s the correct way.
Don’t use a renderer, do all the visual work if possible in the core and let the specific of OAuth to the class.
To do this you create an interface exposing the methods you need to use and then in the specific projects you create a class implementing the interface and decorated with the Dependency attribute.
When you need to use it you ask to the DependencyService for an instance of your interface and it will retrieve the correct class from the specific projects.
Here is the documentation about DependencyService: https://developer.xamarin.com/guides/xamarin-forms/dependency-service/