Skip to content

Instantly share code, notes, and snippets.

@jbristowe
Last active June 29, 2017 21:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jbristowe/c89a7bcae7fc9a035ee7 to your computer and use it in GitHub Desktop.
Save jbristowe/c89a7bcae7fc9a035ee7 to your computer and use it in GitHub Desktop.

A Very Rough Guide to Firebase and NativeScript

Create Plugin

  • mkdir nativescript-firebase
  • cd nativescript-firebase
  • npm init
  • tns init
  • mkdir -p platforms/ios
  • touch platforms/ios/Podfile
  • In platforms/ios/Podfile: pod 'Firebase'
  • mkdir -p platforms/android/libs
  • Copy the Firebase SDK JAR to platforms/android/libs
  • (Optional) touch platforms/android/AndroidManifest.xml
  • (Optional) In platforms/android/AndroidManifest.xml:
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
  <uses-permission android:name="android.permission.INTERNET" />
</manifest>

Import Plugin

  • In your NativeScript project: tns plugin add <location of nativescript-firebase>

Use Plugin on Android

var appModule = require("application");

// ...

var Firebase = com.firebase.client.Firebase;
var ChildEventListener = com.firebase.client.ChildEventListener;

Firebase.setAndroidContext(appModule.android.context);
ref = new Firebase(<Firebase URL>);

ref.addChildEventListener(new ChildEventListener({
	onChildRemoved: function(snapshot) {
		// do your thing
	},
	onChildAdded: function(snapshot, previousChildKey) {
		// do your thing
	},
	onChildChanged: function(snapshot, string) {
		// do your thing
	},
	onChildMoved: function(snapshot, string) {
		// do your thing
	}
}));

To add new items:

var data = new java.util.HashMap();
data.put(...);
ref.push().setValue(data);

To delete items:

ref.child(id).setValue(null);

And so on.

Use Plugin on iOS

var ref = new Firebase(<Firebase URL>);

ref.observeEventTypeWithBlock(FEventType.FEventTypeChildAdded, function (snapshot) {
	// do your thing
});

ref.observeEventTypeWithBlock(FEventType.FEventTypeChildRemoved, function (snapshot) {
	// do your thing
});

ref.observeEventTypeWithBlock(FEventType.FEventTypeChildChanged, function (snapshot) {
	// do your thing
});

To add new items:

ref.childByAutoId().setValue(...);

To delete items:

ref.childByAppendingPath(id).setValue(null);

And so on.

@afortaleza
Copy link

Works like magic! :)

@alexnewgen
Copy link

Thank you for this guide! Have you managed to get user authentication/user signup working? I keep running into syntax errors.

@jbristowe
Copy link
Author

Have you managed to get user authentication/user signup working?

This is left as an exercise for the reader.

Just kidding. I'm hoping to get an actual plugin up & running soon.

@afortaleza
Copy link

I'd like to contribute to this thread with two functions, one to transform a javascript object into a HashMap for insertion into the Firebase database and another to to the opposite, it takes a HashMap and convert it back to javascript.

Javascript object to HashMap

function toHashMap(obj) {
    var node = new java.util.HashMap();
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (obj[property] != null) {
                switch (typeof obj[property]) {
                    case 'object':
                        node.put(property, toHashMap(obj[property], node));
                        break;
                    case 'boolean':
                        node.put(property, java.lang.Boolean.valueOf(String(obj[property])));
                        break;
                    case 'number':
                        if (Number(obj[property]) === obj[property] && obj[property] % 1 === 0)
                            node.put(property, java.lang.Long.valueOf(String(obj[property])));
                        else
                            node.put(property, java.lang.Double.valueOf(String(obj[property])));
                        break;
                    case 'string':
                        node.put(property, String(obj[property]));
                        break;
                }
            }
        }
    };

    return node;
}

You can use like this:

var user = {
    name: viewModel.get("name"),
    lastName: viewModel.get("lastName"),
    address: {
        street: viewModel.get("street"),
        city: viewModel.get("city")
    }
}

var userMap = toHashMap(user);
var refUser = ref.child(viewModel.get("username"));
refUser.setValue(usuarioMap);

HashMap to Javascript object

function toJsObject(javaObj) {
    var node = {};

    var iterator = javaObj.entrySet().iterator();
    while(iterator.hasNext()) {
        item = iterator.next();

        switch (item.getClass().getName()) {
            case 'java.util.HashMap':
                node[item.getKey()] = toJsObject(item.getValue());
                break;
            case 'java.lang.String':
                node[item.getKey()] = String(item.getValue());
                break;
            case 'java.lang.Boolean':
                node[item.getKey()] = Boolean(String(item.getValue()));
                break;
            case 'java.lang.Long':
            case 'java.lang.Double':
                node[item.getKey()] = Number(String(item.getValue()));
                break;
        }

        node[item.getKey()] = item.getValue();
    }

    return node;
}

And you can use like this:

ref.addChildEventListener(new ChildEventListener({
    onChildAdded: function(snapshot, previousChildKey) {
        viewModel.userList.push(toJsObject(snapshot.getValue()));
    }
}

Therefore one can work on the application level with javascript objects only.

@x4080
Copy link

x4080 commented Nov 20, 2015

Hi, I successfully connect in the android but in the ios when I do console.log("ios "+Firebase);
its always undefined, firebase pod already installed maybe theres no metadata generated ?

I added via Podfile and pod install and via plugin still the same result, any tips ?

Thanks

Edit: nevermind, it works on "pageloaded"

and thanks to @afortaleza for conversion, maybe if the conversion is rewritten in java (as a library) will it go faster ?

@x4080
Copy link

x4080 commented Nov 24, 2015

Hi John, did you try the offline firebase capabilities ? In Android seems work but not in IOS

@EddyVerbruggen
Copy link

Hey guys, just wanted to share I'm working on a Firebase plugin for NativeScript based on this Gist. I'm also including the cool recursive JSON to/from Java HashMap methods @afortaleza provided. And for folks interested how iOS deals with this: from JSON to iOS is just fine out of the box, but the way back it's not. You'll get a structure like this:

  user =     {
      address =         {
          number = 123;
          street = foostreet;
      };
      birthYear = 1977;
      first = Eddy;
      isMale = 1;
      last = Verbruggen;
  };

Which can be transformed back to JSON by this function:

firebase.toJsObject = function(objCObj) {
  if (typeof objCObj == "string"||
      typeof objCObj == "number" ||
      typeof objCObj == "boolean") {
    return objCObj;
  }
  var node = {};
  var oKeyArr = objCObj.allKeys;
  for (var i = 0, l = oKeyArr.count; i < l; i++) {
    var key = oKeyArr.objectAtIndex(i);
    var val = objCObj.valueForKey(key);

    switch (types.getClass(val)) {
      case 'NSMutableDictionary':
        node[key] = firebase.toJsObject(val);
        break;
      case 'String':
        node[key] = String(val);
        break;
      case 'Boolean':
        node[key] = Boolean(String(val));
        break;
      case 'Number':
        node[key] = Number(String(val));
        break;
    }
  }
  return node;
};

And can be called like this from one of your observeEventTypeWithBlock methods:

  var value = firebase.toJsObject(snapshot.value)

I'll post a link to the plugin here once it's done.

@EddyVerbruggen
Copy link

It's ready to go, I hope y'all like it: https://github.com/EddyVerbruggen/nativescript-plugin-firebase

@jbristowe
Copy link
Author

👍

Awesome stuff, Eddy!

@lyonzy
Copy link

lyonzy commented Nov 27, 2015

Great minds think alike! I just created the nativescript-firebase plugin on npm based on the Firebase node.js SDK :)
Hey @EddyVerbruggen, just checking out your source - if you want a simpler way to turn Android objects back into JSON I used this slightly hacky but fairly concise trick back when I was using the Firebase Android SDK in {N}:

            var jobj = new org.json.JSONObject(javaObject);
            return JSON.parse(jobj.toString());

It works for objects and arrays but IIRC you'll need to check for strings/ints/etc and return them directly.
I never got around to doing it the other way around but presumably it's a similar concept.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment