Tag Archives: rest json api

Objective-c tutorial – Second part – add Rest JSON API

This part of the tutorial explains, how to add a Rest JSON API to an already created application, which shows posts and comments for a blog. In this tutorial we will connect the application with the rest API of an actual WordPress blog, so we can view the posts and comments of the blog rather than the mock data.

It requires you to be done with the first step of the tutorial.

Adding Rest JSON API to a wordpress blog

A wordpress blog has a native XMLRPC API. I didn’t want ot use it, because consuming XMLRPC services doesn’t seem straight forward in objective-c without using additional libraries. That’s why I decided to install a plugin on my blog, which adds a Rest JSON API. You can find the plugin here (and some extended documentation here).

After installation, you should be able to open /wp-json/posts/ at your blog – this will return the existing posts (latest 10 entries). Additionally, you can use /wp-json/posts/131/comments to view the comments of a post. The number 131 represents the ID of a certain post.

Objective-c implementation

Let’s implement the services in the application, so we can view real posts and comments instead of the mock-data. Open the implementation of AppDelegate and do some objective-c coding.

AppDelegate.m

#import "AppDelegate.h"
#import "Post.h"
#import "PostComment.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCommentsForPostId:) name:@"getComments" object:nil];

    NSMutableArray *tempPosts = [NSMutableArray array];

    NSURL *url = [NSURL URLWithString:@"http://meberhard.me/wp-json/posts"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *repsone, NSData *data, NSError *connectionError) {
        if (data.length > 0 && connectionError == nil) {
            NSDictionary *wpPosts = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            for (id key in wpPosts) {
                NSInteger postId = [[key objectForKey:@"ID"] integerValue];
                NSString *postTitle = [key objectForKey:@"title"];
                Post *tempPost = [[Post alloc] initWithIdAndTitle:postId title:postTitle];
                [tempPosts addObject:tempPost];
            }
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showPosts" object:tempPosts];
    }];

    }

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}

- (void)getCommentsForPostId:(NSNotification*)notification {
    NSMutableArray *commentsToShow = [NSMutableArray array];
    NSNumber *postId = [notification object];

    NSString *restUrl = [NSString stringWithFormat:@"http://meberhard.me/wp-json/posts/%ld/comments", [postId integerValue]];

    NSURL *url = [NSURL URLWithString:restUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data.length > 0 && connectionError == nil) {
            NSDictionary *wpComments = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            for (id key in wpComments) {
                NSInteger commentId = [[key objectForKey:@"ID"] integerValue];
                NSMutableString *commentText = [[NSMutableString alloc] init];
                [commentText appendString:[key objectForKey:@"content"]];
                PostComment *pcom = [[PostComment alloc] initPostCommentWithComIdAndPostId:commentId postId:[postId integerValue] text:commentText];
                [commentsToShow addObject:pcom];
            }
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showComments" object:commentsToShow];
    }];
}

@end

All instructions to create mock-data are now removed. Instead, we added a variable “tempPosts”, which will store the posts as we receive them from the Rest JSON API. The following lines request the posts from the Rest JSON API, here it is used with my blog. The JSON response is stored in a NSDictionary. We iterate over that dictionary and create an object of “Post” for every entry, the “Post” object is added after to the “tempPosts” array. After iterating, we send the notification to show the posts, we use the array containing the posts as object for the notification.

The method “getCommentsForPostId” works in a similar way. We just use a different URL and also add the id of the post to the Rest JSON API call. After iterating over the response, we send a notification and use the comments as object.

After running the application, you should be able to see the posts of your blog. If you select a post, the comments should appear in the second table:

Application after implementing the Rest JSON API

Application after implementing the Rest JSON API.

Other parts of the tutorial:

First step: Implemented the basic application logic, posts and comments exist only as mock-data. Click here to view the post.

Thid step: Implementing core data so posts and comments may be saved locally. Click here to view the post.