close
ios-app-tutorial-using-wordpress-json-api
Let’s make an iOS App tutorial using WordPress JSON API. I use to make wordpress websites, not as a professional but more of a theme customizer. I don’t have any deep php knowledge. I’m not a back-end nor front-end developer I’m kinda in between. But I switched to iPhone apps development after my graduation so one day I searched for this and found this really cool plugin using which made it simple to build iOS applications using WordPress data in JSON form. So to understand this tutorial you need:

  1. Basic Knowledge of how wordpress works or wordpress structure.
  2. Intermediate knowledge of objective c.
But you don’t have to worry about any of that because nothing of this matters. All you need to know is how wordpress works means some basic knowledge of wordpress. When you login to your wp-admin ¬†you are redirected to your dashboard where you can see the following things:

  • So we have a dashboard where highlights of some things like comments, news from wordpress etc are shown.
  • “All in One SEO” is a plugin I’m using for Search Engine Optimization this has nothing to do with this tutorial so ignore it for now.
  • Under posts your posts are shown, you can add new posts or manage posts categories here.
  • Next to that is the media section which hold all your images, videos and other attachments you have used or have not used in your posts, pages or other custom sections.
  • “Forms” is a plugin fully named as “Gravity Forms” used to make forms this has nothing to do with this tutorial so ignore it for now.
  • Pages are the pages. ūüėÄ What else is there to talk about them. Yes, they are not categorized but you can add tags to them etc.
  • Comments is the feedback user can add to your posts or pages.
  • Appearance deals with your site appearance which includes theme sidebar widgets footer, header widgets, menu and sometimes theme options.
  • Plugins are also a useful part which are used to add extra functionality to your wordpress site.
  • Under Users you can manage your site users admin, subscribers etc.
  • Tools are a useful component normally used for importing and exporting wordpress content.
  • Settings deals with the settings for a visitor when he will visit you site what to show him. Also some plugin’s settings are usually under settings.

So that’s pretty much it about the overview of wordpress which you should know about.

What the APP:

Let’s talk about app what it’ll do. The website of which I’ll be making the app is¬†http://myvoiceunheard.com/¬†go ahead explore the site a little.
You can see some posts on the front page as you scroll down to the footer you can see latest blog as and next to it are tweets. (UPDATE Nov 28 2016: The web structure is now changed)

There are two categories of posts on the website.

  1. Stories
  2. Blog
This are the posts under stories categories.
These are the posts under blog categories.

What the app will do is that it consist of 3 tabs one is stories, second is blog and third is contact.

Means stories tab will show stories posts and blog tab will show blog posts and contact will show some other information. Here is a design I made on photoshop for the app clearing the picture of what I wrote above.

Goto plugins > add new and in the search type JSON API

Install the plugin you see and activate it.

That’s it for the wordpress part. Here is the link of documentation of this plugin:¬†https://wordpress.org/plugins/json-api/other_notes/

MVU App (xCode)

Additional libraries used in this app are:

Make sure you download all of them and import in the project.

My Voice Unheard (MVU) app, open xcode make a new single view app.
Start making the design.
Remove the current view controller and add a new navigation controller from the right side where UIObjects are shown. Expand the size of prototype cell height to 178 and add two UIImageView and 2 UILabel (change their color to white) into it and adjust the positioning according to the image given below.
The Image view in the bottom add this image below to it. Yes we hard code it just to give a good feel. Go ahead save this image it’s free to use commercially.
After that add constraints (auto-layout) to it in order for the design to adjust accordingly to different iPhone dimensions.
If you are not comfortable with constraints (auto-layout) you can use the old technique.
Also make two new classes one will have TableViewController as parent and other will be TableViewCell as parent. Assign these classes to your table view. I’ve named it as StoriesTableViewController and StoriesTableViewCell.
Import StoriesTableViewCell.h to your StoriesTableViewController.m
In your StoriesTableViewController.m there will be a method as Р(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section which return 0 change it to 1 for now.
Final Version will be:

After that there will be a method commented out in the code as Р(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath uncomment it and write:

Run the app and you’ll get something like this:
So here is what we have done so far:
  1. Installed JSON API plugin on wordpress
  2. Created a general design for iOS app
Now lets add some more things into our design. As I said earlier that the app will consist of 3 tabs and we need to have it in our design so we will add a tab bar controller.
One simple way to do that is you select your TableViewController and from the menu above select editor > embed in > tab bar controller. See the image below:
and You’ll have this on your Storyboard now.
So now change the item to stories and add an image to it. For now I’ll only work on this screen and complete the tutorial and in the end there will be a practice task for you in order to test your learnings.
So, now is the time we start the API.

Calling JSON API Plugin:

After reading the documentation of JSON API plugin here: https://wordpress.org/plugins/json-api/other_notes/ I came to know that calling the api is simple. But my pick from this were:
  • You can GET all the posts on your wordpress.
  • You can filter GET all the post based on the specific category.
  • You can also apply count in¬†filter.

Calling the API is as simple as www.example.com/api and add to it what type of data you want. So, in my case I want Get All Stories Category Posts.

Let’s break it down a little:
Get :¬†It’s¬†a GET call
All  : Everything under the category. i.e. All the posts
Stories : Our category name/slug
Category : We are apply filter based on category
Posts : Our output is we need posts
 
Here is the link which will give me all of this:

http://myvoiceunheard.com/api/?json=get_category_posts&category_slug=stories&count=-1

So my JSON call is to get category post where category slug is stories and count is -1.
Count can be zero if there are no posts but -1 means infinity so it’ll get all the posts. Pretty simple right.
Run this link on a browser and you see the data. Find a formatter and see this data in a more readable form. I use postman app on chrome so here is how it responds to me:

Understanding JSON

Let’s understand the structure of this JSON which wordpress returns. But it is mandatory that you already understand the basic structure of JSON i.e. [] indicates array {} indicates objects etc.
Rewind in mind the process you do for publishing a post on wordpress.
This is the response:
I’ve just compressed the response for better understanding. This data is the response to my call and I got 14 posts which is correct because I actually have 14 posts in my stories category and under “posts” I got 14 objects. For now the data I want to use is under “posts” so lets extract one posts object and see what is inside that:
So for a single post we have it’s id, type, slug, url, status, title, title_plain, content, excerpt, date, modified, categories, tags, author, comments, attachments, comment_count, comment_status, thumbnail, custom_fields, thumbnail_size, thumbnail_images
The bold text means that these object contains more object into it. And in some cases like attachments there is an other array. So it’s kinda nested array.
Let open the attachment array and see what is inside that:
So on of the object under attachment contains id, url, slug, title, description, caption, parent, mime_type, images > full, thumbnail, medium, large.
So you see this is pretty much what you do while publish a post on wordpress. Extracting large section we get:
Large have the url of image. So now you have the URL you can use it to show the image in your app.
Now the question is that what we need from it? We don’t need all the objects we need just some and will ignore the rest. So in this app case I need:
  • title
  • content
  • date
  • attachment > images > large
So this is the way all the 14 objects are in the response. So let’s open xcode and see what happens there.

Showing JSON data on the app

Here we go the first thing you need to do is include AFNetworking framework in your project. Download the latest version from GitHub by clicking on Download Zip.
When you unzip you see a lot of things but all you need to do is to copy two folders into it as shown in the image below:

Now go ahead and open your StoriesTableViewController.m and¬†#import “AFNetworking.h”
After that #import line type¬†static NSString * const BaseURLString = @”http://myvoiceunheard.com/api/”;

Before we jump into calling and parsing our JSON we first need to make some changes in StoriesViewController.h which is to initialize some arrays and dictionary for the purpose of storing data into it.

and some NSMutableArray

So you final class will look like this:

Let’s make a method called getAllStories as -(void)getAllStories{} and in that method we will parse our json.
Make sure you have declared a base URL just after #import ends¬†static¬†NSString¬†*¬†const¬†BaseURLString =¬†@”http://myvoiceunheard.com/api/”;

Okay so inside that function You first create a string representing the full url from the base URL string. This is then used to create an NSURL object, which is used to make an NSURLRequest.

After that we call the AFHTTPRequestOperation which is an all-in-one class for handling HTTP transfers across the network. You tell it that the response should be read as JSON by setting the responseSerializer property to the default JSON serializer. AFNetworking will then take care of parsing the JSON for you.

This operations has two blocks one is setCompletionBlockWithSuccess and failure. So after that write [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { }

Now the major parsing starts.
First of all save all the data you retrieved from JSON into NSDictionary as self.allStoriesDict = (NSDictionary *)responseObject;
Now all the game which is left is in arrays and objects. As I described the JSON above I know that I’ve all the data in Posts. So now that I have the data in a dictionary we will move hierarchy wise, it’s like every time you open a door (save first level of JSON response in an Array or Dictionary) it gave you the key of the next level. So let’s save all 14 posts objects in the array.

Make sure the valueForKey is the same as it is in JSON. So here what we did is that we¬†initialized¬†the array and¬†then we took data from dictionary for posts value. If you print allStoriesPosts.count here it’ll give you 14.

Now that you’re in posts you need title first. Take is as:


 

So we did the same now but as you can see we did it from allStoriesPosts. As by opening the door of allStoriesPosts from AllStoriesDict we obtained key for a lot of doors(objects under posts).
So now we have the titles we need date. For date do the same:
Just the valueForKey is changed rest is the same.
Next thing I need is an image to display. After viewing my JSON I came to know the hierarchy for that which is:
thumbnail_images > medium > url
So it’s like I have to open thumbnail_images and then inside of that I have large, full, medium and small but I need medium only so I’ll open medium block and inside that medium block I’ll get my URL.
To open the thumbnail_images do the same you did for title and date.

 

Now there is a chance that any post is not using the image so it’ll be empty you can have a check over that. But I am not using it here for now.
Now let’s call all the medium images:
So now you see I picked key of medium from allThumbnailImages array. It all depends on the hierarchy. Now the major thing which is url of the images:
 
See how simple it is. Now go ahead and try getting the “content” and “url” of “posts” as a self do task.
and after that make sure you call reloadData on you tableview as [self.tableView reloadData];.
Now you have everything you need to display. Just write NSAlert in failure so that you’ll know of your call fails.

and after that just one more thing to start the operation write¬†[operation start]; after failure block ends.¬†You must explicitly tell the operation to ‚Äústart‚ÄĚ (or else nothing will happen).
My final method looks like this:

after [self.tableview reloadData]; starts your failure block.

So finally we have some data that we can display on the table cells that we have.

So this is the first function that will number of rows we need in total. You can use any array, I’ve used title array. So it will return 14. You can also use “count” from allStoriesDict here. You just need to know how many rows you’ll be needing. Do whatever you feel is easy.

Now the next delegate function is:

We initialized an object of StoriesTableViewCell and after that we set the title from fetching the title from title array and similarly we did the same with date and for image we use an additional library SDWebImage but called the url from the URL array.

Now we have everything set up just perfectly. Follow are some additional steps I’m doing you can ignore them if you want and run the app just now. But there are some issue in the data of JSON that needs to be fixed but we can ignore them.

  1. Title of some posts have special characters like “-” and these are converted to – which are called¬†html-entities. So this has to be converted back to simple “-“
  2. The date JSON is retriving is good to use but it’s¬†something¬†like this¬†2015-11-22 15:19:07 and I need it as 22-11-2015.
So these are the two issues I’m solving below.
For first problem where I’ve taken the title I’ll do this:

It’s very simple. Just read it as str if ≵ occurs replace it with string –
I’ve also hard coded some more tags just to be on a safe side. Run it now and you’ll see problem number one is fixed.
For problem number two make a method.

So it takes a string which is the date and it’s format is the same as I’m getting from JSON it converts it to a new format and returns it in string.

just call the conversion method before setting the date to label.

Here is a screen shot of my code:

That’s it. RUN THE PROJECT and see what progress have we made.
  1. Project will start loading. I’ve used MBProgressHUD to show the loading HUD.
  2. If the call is successful the stories will be loaded in the ViewController.
  3. Scroll up and down to see it is smooth and loading all the content.
So here you go. You had a wordpress website you have generated JSON from it and parsed it inside you app and now your website have an app.

What’s Next?

Now you have to decide when a user selects a story what will happen. In my case I’m displaying another ViewController which is showing the content in a webview. Content if you see your JSON is in HTML format (means it has html tags). You’ll do all this in a delegate method of your table view:

figure out and do something that will help user to read the story.

Also do the same for blog category. Call and display blog category posts. If you have any questions ask them in comments.

Tags : iOS App tutorial using Wordpress JSON APIJSON APIjson api ios appWordpress
Chaudhary Talha

The author Chaudhary Talha

I'm an iOS developer by profession and UI/UX designer by passion. All my tutorials are based on my personal experiences and whenever I learn something new I share it with the world.