Build Data Driven IOS & Android Apps With WordPress REST API & NativeScript – Part 3

The WP Crowd
Published: August 1, 2016

Be sure to check out Part 1 and Part 2 of the series to get caught up on integrating the WP REST API into NativeScript {N}.

You can download the git repo of the final, functioning demo below.  If you’ve created the project as we outlined in the earlier posts then you just put this inside the /app directory:
https://github.com/ChrisFlannagan/nativescript-wp-rest-api

Connecting WordPress & NativeScript {N}

In this final post of the series we are going to connect our mobile app with the WordPress REST API.  To do this, let’s start back where we left off.  Open up the main-page.xml file and let’s do some tweaking.

First let’s replace the

navigatingTo="onNavigatingTo"

in the opening <Page> tag and replace with

loaded="loaded"

We want to run our main function after all the xml has been loaded.

Let’s go ahead and replace all of it with the below xml.  Things to note: We have a ListView now that we will populate, the button has been removed as we are going to auto hit the REST API on load and we have some variable names: postList and postName.

We want to have a ListView here.  We are going to fill this with our data from the REST API.  Each post will have a ListView.itemTemplate made for it including the Label view which will contain the name of the post.

These placeholder variables wrapped in {{ and }} are how we connect our data between JavaScript and the XML file.

Gathering Our Data

Open up main-page.js and go ahead and delete everything in there, we are going to start from scratch.  Paste this code into your main-page.js file:

Now let’s analyze this.

What’s Happening in main-page.js

The very first thing we do is declare var page.  This is not a requirement but we are going to set that as the page object, think of it like the DOM.

When main-page.xml is loaded it fires off main-page.js at the same time.  There are quite a few functions you can declare in your xml file on the <Page> tag but the most comming is loaded.  It’s like $(document) in jQuery, it fires that function when the page xml is completely loaded.

If you look in the xml file you will see that <Page> has loaded=”loaded” on it that we just placed there.  When calling functions in the xml we do not use parenthesis.

If we want a function to be accessible to the xml it must be placed in the exports object, hence our code exports.loaded = function(args).  The args brings in the page object which we can now manipulate and read.

The GET Request

Note: I am using version 2 of the WP REST API

In this function we define our page object variable then we launch a fetch request.  Fetch API is built into {N} core so we do not have to use an include statement.

If we want to add some parameters to our query we can put them on the end of the url.  If you are making a POST request, you can put them in the body: area.  I’m not sure if POST works with the REST API though, so ask your resident REST API expert or tweet Josh Polluck. Your request could  then look like:

… if you want to grab the top five posts from a specific category called “Tutorials.”

We handle the return by tacking on the then() function, first to handle any errors and you can see our nifty error handling function at the bottom of the script.

Second then(data) is to actually handle the data.  We pass that data in with a variable called “posts” and then, just like normal JavaScript, we console.log but with console.dump here since we want to see the object’s innards.

shazzam-shaq-magic-wordpress-rest-api-nativescript

Kazzam! You can see your returned post json from the REST API!

Let’s Purdy It Up

Don’t worry, not going to leave you hanging.  We are actually going to make this data look good and put it visually in the app.  Let’s do some data binding.

First let’s loop through our posts and grab what we need.  Replace the console.dump(posts) with:

Check your log, you should see each posts title coming through now.

Bind It

To push this data into the ListView we need to require a couple classes starting with Observable and ObservableArray.  This creates an object that is observed and can perform a function when anything is added or removed from it and the latter builds an array to hold each Observable for our list.

So at the very tip-top of our file let’s add these lines:

Declaring require() on a variable is how we include libraries, plugins and classes in our {N} app pages.

Building The ObservableArray

In the beginning of our loaded function we need to now declare an empty ObservableArray object then bind it to the postsList, ListView on our xml page.  So replace the top line page = args.object with the following (notice that line is still in there in the middle of the new code):

postTitles is our array of Observables which are turned into items in the ListView.  We declare it empty with [] then map it to a function that returns an Observable object.  That Observable has one property, postName, which is assigned the value of postTitle which is being passed in as a parameter.

We bind this array to our xml ListView by setting the page.bindingContext.  We establish in this line that if there is a ListView with the items parameter with the value set as postList, it is now bound to our ObservableArray object.  Since a ListView is an array it performs properly.

In our forEach loop of the posts we need to push each post title into our new postTitles ObservableArray.  So we push in objects one at a time with one value each which is picked up by our mapped function.  Voila! We have data on our app’s main page!

CSS

Last but not least, let’s make this look even better and show you the css ropes while we are at it.  Create a file named main-page.css.  Again, it’s vital that the .js, .xml and .css files have the same name.  You can include others of a different name but this is the best convention for auto-including a .js and .css combination with your xml page.

Now just put this or your own styles in and save.  Note: The use of px, pt or other sizing methods are not usable in NativeScript other than %.  It’s just pixels as of now and requires you to put nothing after the number.

Remember you can launch and livesync your app by opening your terminal, browsing to your project’s root directory and typing

tns livesync ios –emulator –watch

Here’s a little video demo I made real fast of launching the application and even applying a change in text color that updates automatically in the emulator since we are using livesync.

Conclusion

I really hope you have enjoyed this series. I’ve enjoyed writing it!  NativeScript is super fun to get into and the REST API is growing more awesomer every single day.  Putting the two together provides some powerful tools at your fingertips.

The final main-page.js file can be copied from here:

Get the latest from The WP Crowd

Leave a Reply

6 Comments on "Build Data Driven IOS & Android Apps With WordPress REST API & NativeScript – Part 3"

avatar
Sort by:   newest | oldest
trackback

[…] Build Data Driven IOS & Android Apps With WordPress REST API & NativeScript – Part 3 […]

Erwin
Guest

Great part again!

I’m gonna try to build an app with it. I wanna have a screen with a menu-bar at the bottom with 3 icons represent three categories in wordpress. It should open an page with a WrapLayout with featured images, there is an add-on for WP-REST api. That image should lead them to the post. So, I do have to make my own puzzle, but I’m enthousiast and I’m believing this could work.

Thank you very much!

trackback

[…] Part 3 is available here. […]

wpDiscuz