Fecha fin: 8-04-2019
Actividades
- Conectar Firebase con el proyecto. (10)
- Corregir el archivo readme.md. (1)
¿Qué hice hasta hoy?
- Conectar Firebase con el proyecto.
Cree el proyecto en firebase.google.com, agregué las apps para Android y iOS

Luego, mientras registraba la app para Android tuve que buscar el certificado SHA-1 por lo que seguí el tutorial que me indicaban en la pagina para conseguirlo.
Por ultimo, cree los archivos e instalé los NuGet's necesarios para poder conectarse a la base en los diferentes proyectos de Android y iOS
Cree dos interfaces comunes para poder utilizarlas en ambos proyectos:
IFirebaseAuthService.cs
Code: Select all
namespace SMove.Services
{
using System;
using System.Threading.Tasks;
public interface IFirebaseAuthService
{
String getAuthKey();
bool IsUserSigned();
Task<bool> SignUp(String email, String password);
Task<bool> SignIn(String email, String password);
void SignInWithGoogle();
Task<bool> SignInWithGoogle(String token);
Task<bool> Logout();
String GetUserId();
}
}
Code: Select all
using System;
using System.Collections.Generic;
using System.Text;
namespace SMove.Services
{
public interface IFirebaseDBService
{
void Connect();
void GetMessage();
void SetMessage(String message);
string GetMessageKey();
void DeleteItem(string key);
}
}
FirebaseAuthService.cs
Code: Select all
namespace SMove.Droid
{
using System;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Firebase.Auth;
using SMove.Services;
using Xamarin.Forms;
public class FirebaseAuthService : IFirebaseAuthService
{
public static int REQ_AUTH = 9999;
public static string KEY_AUTH = "auth";
public string getAuthKey()
{
return KEY_AUTH;
}
public bool IsUserSigned()
{
var user = Firebase.Auth.FirebaseAuth.GetInstance(MainActivity.app).CurrentUser;
var signedIn = user != null;
return signedIn;
}
public async Task<bool> Logout()
{
try
{
Firebase.Auth.FirebaseAuth.GetInstance(MainActivity.app).SignOut();
return true;
}
catch (Exception)
{
return false;
}
}
public async Task<bool> SignIn(string email, string password)
{
try
{
await Firebase.Auth.FirebaseAuth.GetInstance(MainActivity.app).SignInWithEmailAndPasswordAsync(email, password);
return true;
}
catch (Exception)
{
return false;
}
}
public void SignInWithGoogle()
{
var googleIntent = new Intent(Forms.Context, typeof(GoogleLoginActivity));
((Activity)Forms.Context).StartActivityForResult(googleIntent, REQ_AUTH);
}
public async Task<bool> SignInWithGoogle(string token)
{
try
{
AuthCredential credential = GoogleAuthProvider.GetCredential(token, null);
await Firebase.Auth.FirebaseAuth.GetInstance(MainActivity.app).SignInWithCredentialAsync(credential);
return true;
}
catch (Exception)
{
return false;
}
}
public async Task<bool> SignUp(string email, string password)
{
try
{
await Firebase.Auth.FirebaseAuth.GetInstance(MainActivity.app).CreateUserWithEmailAndPasswordAsync(email, password);
return true;
}
catch (Exception)
{
return false;
}
}
public string GetUserId()
{
var user = Firebase.Auth.FirebaseAuth.GetInstance
(MainActivity.app).CurrentUser;
return user.Uid;
}
}
}
Code: Select all
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using Firebase.Auth;
using Android.App;
using Android.Content;
using Firebase.Database;
using SMove.Droid.Servicios;
using System.Collections.ObjectModel;
using System.Linq;
using SMove.Services;
[assembly: Dependency(typeof(FirebaseDBService))]
namespace SMove.Droid.Servicios
{
public class ValueEventListener : Java.Lang.Object, IValueEventListener
{
public void OnCancelled(DatabaseError error) { }
public void OnDataChange(DataSnapshot snapshot)
{
String message = snapshot.Value.ToString();
MessagingCenter.Send(FirebaseDBService.KEY_MESSAGE, FirebaseDBService.KEY_MESSAGE, message);
}
}
public class FirebaseDBService : IFirebaseDBService
{
DatabaseReference databaseReference;
FirebaseDatabase database;
FirebaseAuthService authService = new FirebaseAuthService();
public static String KEY_MESSAGE = "items";
public void Connect()
{
database = FirebaseDatabase.GetInstance(MainActivity.app);
}
public void GetMessage()
{
var userId = authService.GetUserId();
databaseReference = database.GetReference("items/" + userId);
databaseReference.AddValueEventListener(new ValueEventListener());
}
public string GetMessageKey()
{
return KEY_MESSAGE;
}
public void SetMessage(string message)
{
var userId = authService.GetUserId();
databaseReference = database.GetReference("items/" + userId);
String key = databaseReference.Push().Key;
databaseReference.Child(key).SetValue(message);
}
public void DeleteItem(string key)
{
var userId = authService.GetUserId();
databaseReference = database.GetReference("items/" + userId);
databaseReference.Child(key).RemoveValue();
}
}
}
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V7.App;
using Android.Gms.Common.Apis;
using Android.Gms.Common;
using System.Threading.Tasks;
using Android.Gms.Auth.Api.SignIn;
using Android.Gms.Auth.Api;
using Firebase.Auth;
namespace SMove.Droid
{
[Activity(Label = "GoogleLogin", Theme = "@style/Theme.AppCompat.Light.DarkActionBar")]
public class GoogleLoginActivity : AppCompatActivity, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener
{
const string TAG = "GoogleLoginActivity";
const int RC_SIGN_IN = 9001;
const string KEY_IS_RESOLVING = "is_resolving";
const string KEY_SHOULD_RESOLVE = "should_resolve";
static GoogleApiClient mGoogleApiClient;
bool mIsResolving = false;
bool mShouldResolve = false;
private static GoogleSignInAccount mAuth;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
String token = "745578531830-t2k4mc0gepe64h0ad6iolo2svgjaoa7n.apps.googleusercontent.com";
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn).RequestIdToken(token).Build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(this)
.AddApi(Auth.GOOGLE_SIGN_IN_API, gso)
.Build();
Intent signInIntent = Auth.GoogleSignInApi.GetSignInIntent(mGoogleApiClient);
StartActivityForResult(signInIntent, RC_SIGN_IN);
}
private void HandleResult(GoogleSignInAccount result)
{
if (result != null)
{
Intent myIntent = new Intent(this, typeof(GoogleLoginActivity));
myIntent.PutExtra("result", result);
SetResult(Result.Ok, myIntent);
}
Finish();
}
private async void UpdateData(bool isSignedIn)
{
if (isSignedIn)
{
HandleResult(mAuth);
}
else
{
await System.Threading.Tasks.Task.Delay(2000);
mShouldResolve = true;
mGoogleApiClient.Connect();
}
}
protected override void OnStart()
{
base.OnStart();
mGoogleApiClient.Connect();
}
protected override void OnStop()
{
base.OnStop();
mGoogleApiClient.Disconnect();
}
protected override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState);
outState.PutBoolean(KEY_IS_RESOLVING, mIsResolving);
outState.PutBoolean(KEY_SHOULD_RESOLVE, mIsResolving);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN)
{
var result = Android.Gms.Auth.Api.Auth.GoogleSignInApi.GetSignInResultFromIntent(data);
if (result.IsSuccess)
{
// Google Sign In was successful, authenticate with Firebase
HandleResult(result.SignInAccount);
}
else
{
// Google Sign In failed, update UI appropriately
HandleResult(null);
}
}
}
public void OnConnected(Bundle connectionHint)
{
UpdateData(false);
}
public void OnConnectionSuspended(int cause) { }
public void OnConnectionFailed(ConnectionResult result)
{
if (!mIsResolving && mShouldResolve)
{
if (result.HasResolution)
{
try
{
result.StartResolutionForResult(this, RC_SIGN_IN);
mIsResolving = true;
}
catch (IntentSender.SendIntentException e)
{
mIsResolving = false;
mGoogleApiClient.Connect();
}
}
else
{
ShowErrorDialog(result);
}
}
else
{
UpdateData(false);
}
}
class DialogInterfaceOnCancelListener : Java.Lang.Object, IDialogInterfaceOnCancelListener
{
public Action<IDialogInterface> OnCancelImpl { get; set; }
public void OnCancel(IDialogInterface dialog)
{
OnCancelImpl(dialog);
}
}
void ShowErrorDialog(ConnectionResult connectionResult)
{
int errorCode = connectionResult.ErrorCode;
if (GoogleApiAvailability.Instance.IsUserResolvableError(errorCode))
{
var listener = new DialogInterfaceOnCancelListener();
listener.OnCancelImpl = (dialog) =>
{
mShouldResolve = false;
};
GoogleApiAvailability.Instance.GetErrorDialog(this, errorCode, RC_SIGN_IN, listener).Show();
}
else
{
mShouldResolve = false;
}
HandleResult(mAuth);
}
}
}
FirebaseAuthService.cs
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Firebase.Auth;
using Foundation;
using SMove.Services;
using UIKit;
using Xamarin.Auth;
using Xamarin.Forms;
using SMove.iOS.Servicios;
[assembly: Dependency(typeof(FirebaseDBService))]
namespace SMove.iOS
{
public class FirebaseAuthService : IFirebaseAuthService
{
public static String KEY_AUTH = "auth";
public static OAuth2Authenticator XAuth;
private static bool hasLoginResult = false;
private static bool loginResult = false;
private static bool signUpResult = false;
CancellationTokenSource tokenSource;
CancellationToken token;
Task t;
public IntPtr Handle => throw new NotImplementedException();
public string getAuthKey()
{
return KEY_AUTH;
}
public string GetUserId()
{
var user = Auth.DefaultInstance.CurrentUser;
return user.Uid;
}
public bool IsUserSigned()
{
var user = Auth.DefaultInstance.CurrentUser;
return user != null;
}
public async Task<bool> Logout()
{
NSError error;
var signedOut = Auth.DefaultInstance.SignOut(out error);
if (!signedOut)
{
return false;
}
return true;
}
//LOGIN USER/PASS
public async Task<bool> SignIn(string email, string password)
{
Auth.DefaultInstance.SignIn(email, password, HandleAuthResultLoginHandler);
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
t = Task.Factory.StartNew(async () =>
{
await Task.Delay(4000);
}, token).Unwrap();
await t;
return loginResult;
}
private void HandleAuthResultLoginHandler(User user, Foundation.NSError error)
{
if (error != null)
{
loginResult = false;
hasLoginResult = true;
}
else
{
loginResult = true;
hasLoginResult = true;
}
tokenSource.Cancel();
}
public async Task<bool> SignInWithGoogle(string tokenId)
{
String[] tokens = tokenId.Split(new string[] { "###" }, StringSplitOptions.None);
var credential = GoogleAuthProvider.GetCredential(tokens[0], tokens[1]);
Auth.DefaultInstance.SignIn(credential, HandleAuthResultHandlerGoogleSignin);
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
t = Task.Factory.StartNew(async () =>
{
await Task.Delay(4000);
}, token).Unwrap();
await t;
return loginResult;
}
private void HandleAuthResultHandlerGoogleSignin(User user, NSError error)
{
if (error != null)
{
loginResult = false;
hasLoginResult = true;
}
else
{
loginResult = true;
hasLoginResult = true;
}
tokenSource.Cancel();
}
public void SignInWithGoogle()
{
XAuth = new OAuth2Authenticator(
clientId: "745578531830-21hn7vjqkteplcblr9sgiai7ovjk1nil.apps.googleusercontent.com",
clientSecret: "",
scope: "profile",
authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/v2/auth"),
redirectUrl: new Uri("com.googleusercontent.apps.745578531830-21hn7vjqkteplcblr9sgiai7ovjk1nil:/oauth2redirect"),
accessTokenUrl: new Uri("https://www.googleapis.com/oauth2/v4/token"),
isUsingNativeUI: true);
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
XAuth.Completed += OnAuthenticationCompleted;
XAuth.Error += OnAuthenticationFailed;
var viewController = XAuth.GetUI();
vc.PresentViewController(viewController, true, null);
}
private void OnAuthenticationCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
vc.DismissViewController(true, null);
if (e.IsAuthenticated)
{
var access_token = e.Account.Properties["access_token"].ToString();
var id_token = e.Account.Properties["id_token"].ToString();
MessagingCenter.Send(FirebaseAuthService.KEY_AUTH, FirebaseAuthService.KEY_AUTH, id_token + "###" + access_token);
}
else
{
//Error
}
}
private void OnAuthenticationFailed(object sender, AuthenticatorErrorEventArgs e)
{
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
vc.DismissViewController(true, null);
}
public async Task<bool> SignUp(string email, string password)
{
Auth.DefaultInstance.CreateUser(email, password, HandleAuthResultHandlerSignUp);
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
t = Task.Factory.StartNew(async () =>
{
await Task.Delay(4000);
}, token).Unwrap();
await t;
return signUpResult;
}
private void HandleAuthResultHandlerSignUp(User user, Foundation.NSError error)
{
if (error != null)
{
signUpResult = false;
hasLoginResult = true;
}
else
{
signUpResult = true;
hasLoginResult = true;
}
tokenSource.Cancel();
}
}
}
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Firebase.Database;
using Foundation;
using SMove.iOS.Servicios;
using SMove.Services;
using UIKit;
using Xamarin.Forms;
[assembly: Dependency(typeof(FirebaseDBService))]
namespace SMove.iOS.Servicios
{
public class FirebaseDBService : IFirebaseDBService
{
public static String KEY_MESSAGE = "items";
private FirebaseAuthService authService = new FirebaseAuthService();
DatabaseReference databaseReference;
public void Connect()
{
databaseReference = Database.DefaultInstance.GetRootReference();
}
public void GetMessage()
{
var userId = authService.GetUserId();
var messages = databaseReference.GetChild("items").GetChild(userId);
nuint handleReference2 = messages.ObserveEvent(DataEventType.Value, (snapshot) =>
{
//var folderData = snapshot.GetValue();
// Do magic with the folder data
String message = "";
if (snapshot.GetValue() != NSNull.Null)
{
message = snapshot.GetValue().ToString();
}
MessagingCenter.Send(FirebaseDBService.KEY_MESSAGE, FirebaseDBService.KEY_MESSAGE, message);
});
}
public void SetMessage(String message)
{
var userId = authService.GetUserId();
var messages = databaseReference.GetChild("items").GetChild(userId).Reference;
var key = messages.GetChildByAutoId().Key;
messages.GetChild(key).SetValue((NSString)message);
}
public String GetMessageKey()
{
return KEY_MESSAGE;
}
public void DeleteItem(string key)
{
var userId = authService.GetUserId();
var messages = databaseReference.GetChild("items").GetChild(userId).Reference;
messages.GetChild(key).RemoveValue();
}
}
}
Cambie la descripción del archivo readme del proyecto

¿Qué voy a hacer?
- Verificar si se está conectando correctamente a la base de datos
- Planear Sprint #11
¿Qué problemas he tenido?
Ninguno durante este Sprint.
Velocidad inicial: 11
Velocidad final: 11
Burndown chart:
