Upgrade to Pro — share decks privately, control downloads, hide ads and more …

BackendLESS Apps - how and why?

BackendLESS Apps - how and why?

Slides of the talk given at AppBuilders CH 2017, in Lausanne, together with Matteo Bonifazi

Roberto Orgiu

April 24, 2017
Tweet

More Decks by Roberto Orgiu

Other Decks in Technology

Transcript

  1. AUTHENTICATE ANONYMOUSLY mAuth.signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void

    onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInAnonymously:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInAnonymously:failure", task.getException()); Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } // ... } });
  2. LET'S LOGIN BY FACEBOOK PROVIDER // Initialize Facebook Login button

    mCallbackManager = CallbackManager.Factory.create(); facebookLoginButton.setReadPermissions("email", "public_profile"); facebookLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Log.d(TAG, "facebook:onSuccess:" + loginResult); handleFacebookAccessToken(loginResult.getAccessToken()); } });
  3. HANDLE THE TOKEN & SEND TO FIREBASE private void handleFacebookAccessToken(AccessToken

    token) { AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); ... } else { // Signature failed somehow... } } }); }
  4. FROM ANONYMOUS TO PERMANENT AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); mAuth.getCurrentUser().linkWithCredential(credential) .addOnCompleteListener(this,

    new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser user = task.getResult().getUser(); } else { Log.w(TAG, "linkWithCredential:failure", task.getException()); ... } // ... } });
  5. AFTER ALL WE WOULD LIKE TO SIGNOUT public void signOut()

    { //Signout from Firebase mAuth.signOut(); //Signout from the specif provider - Facebook in this case LoginManager.getInstance().logOut(); ... }
  6. IMPLEMENTING PUSH MANAGEMENT class PushService : FirebaseMessagingService() { override fun

    onMessageReceived(remoteMessage: RemoteMessage) { ... } override fun onDeletedMessages() { ... } }
  7. IMPLEMENTING PUSH MANAGEMENT App state Notification Data Both Foreground onMessageRece

    ived() onMessageRece ived() onMessageRece ived() Background System tray onMessageRece ived() system tray! > Notification in the system tray, Data in extras of the intent.
  8. IMPLEMENTING TOKEN MANAGEMENT class TokenManagementService : FirebaseInstanceIdService() { override fun

    onTokenRefresh() { val token = FirebaseInstanceId.getInstance().token } }
  9. // Create a storage reference from our app StorageReference storageRef

    = storage.getReference(); // Create a reference to filename StorageReference mountainsRef = storageRef.child("pippo.jpg"); // Create a reference to 'images/pippo.jpg' StorageReference mountainImagesRef = storageRef.child("images/pippo.jpg");
  10. UPLOAD THE FILE Uri file = Uri.fromFile(new File("path/to/images/simpaty.jpg")); StorageReference riversRef

    = storageRef.child("images/"+file.getLastPathSegment()); uploadTask = riversRef.putFile(file); // Register observers to listen for when the download is done or if it fails uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle unsuccessful uploads } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL. Uri downloadUrl = taskSnapshot.getDownloadUrl(); } });
  11. DOWNLOAD THE FILE fileRef = storageRef.child("images/local.jpg"); File localFile = File.createTempFile("images",

    "jpg"); fileRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { // Local temp file has been created } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
  12. MONITOR UPLOAD/DOWNLOAD TASK Task state Task action Listener Type Pause

    pause() OnPausedListener Failure/Cancel cancel() OnFailureListener Resume resume() OnProgressListener Success -- OnSuccessListener
  13. WRITE TO YOUR DATABASE // Write a message to the

    database FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("node_XX"); myRef.setValue("Hello, World!");
  14. LISTEN AND READ FOR ANY VALUE EVENTS // Read from

    the database myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. String value = dataSnapshot.getValue(String.class); Log.d(TAG, "Value is: " + value); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); } });
  15. CLOUD FUNCTIONS > Run without a backend > No maintenance

    > Automatic scaling > Detached from the client > Based on triggers
  16. myproject +- .firebaserc # Hidden file that helps you quickly

    switch between | # projects with `firebase use` | +- firebase.json # Describes properties for your project | +- functions/ # Directory containing all your functions code | +- package.json # npm package file describing your Cloud Functions code | +- index.js # main source file for your Cloud Functions code | +- node_modules/ # directory where your dependencies (declared in # package.json) are installed
  17. myproject +- .firebaserc | +- firebase.json | +- functions/ |

    +- src/ | +- main/ | +- kotlin/ # we put our code here
  18. Index.kt fun main(args: Array<String>) { var functions = require('firebase-functions'); exports.myFunc

    = functions.https.onRequest {req, res -> res .status(200) .type("application/json") .send(json) } }