Fetching Wordpress JSON data via URL for an iOS app
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I'm currently using the following code to pull data from a static JSON file inside my iOS app:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    navigationController.delegate = self;

    NSString* jsonFile = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/app.json"];
    NSString* jsonString = [NSString stringWithContentsOfFile:jsonFile encoding:NSUTF8StringEncoding error:nil];
    @try {
        RootViewController* rootViewController = (RootViewController*)[navigationController.viewControllers objectAtIndex:0];
        rootViewController.feed = [[jsonString JSONValue] objectForKey:@"thefeed"];
        [self.window addSubview:navigationController.view];

    @catch (NSException * e) { }

    [self.window makeKeyAndVisible];

    return YES;

It works like I want it to for static data, but I need it to work dynamically via a live url instead. I'm using the Wordpress REST API to kick out the JSON I want over here

I've tried several variations of the following without much luck:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    navigationController.delegate = self;

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:MILKNSUGAR_URL]];
    NSURLConnection* Connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (Connection)
        self.feed = [NSMutableData data];

    [self.window addSubview:loadingView];
    [self.window makeKeyAndVisible];

    return YES;

Thank you!

awarded to alex

Crowdsource coding tasks.

1 Solution

Winning solution

Using the AppDelegate to process these requests is not usually a good idea, so I implemented the methods to make this request work in a UIViewController called ViewController. Basically the code sends a GET request for the json file and then logs the id and title of the posts.

In your ViewController.h file:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSURLConnectionDelegate>
    NSMutableData *_responseData;


In your ViewController.m file:

#import "ViewController.h"

@interface ViewController ()


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // call the data loading method
    [self loadData];

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

- (void)loadData {
    // Create the request.
    NSURL *url = [NSURL URLWithString:@"http://milknsugar.com/wp-json/posts?filter%5Bposts_per_page%5D=50&filter%5Border%5D=DESC"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.timeoutInterval = 20;

    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

# pragma mark - NSURLConnection Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now

    // parse JSON data
    NSError *error = nil;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:_responseData

    if (error == nil) {
        // reponse is valid json and was parsed
        for (int i = 0; i < [arr count]; i++) {
            NSDictionary *dict = [arr objectAtIndex:i];
            NSLog(@"ID: %@, title: %@", [dict objectForKey:@"ID"], [dict objectForKey:@"title"]);

            // do other parsing here
    } else {
        // check error variable

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var


The output should look something like this:

ID: 5236, title: Beolit 15
ID: 5223, title: Bottle Humidifier
ID: 5230, title: Pebble 01
ID: 5216, title: Moire Side Table
ID: 5202, title: The Slit
ID: 5188, title: Borough Skillet
ID: 5184, title: Sunset Print
ID: 5118, title: Tasca
ID: 5153, title: Giveaway: Risograph Calendar
ID: 5142, title: 301 Beanie
ID: 5136, title: Beauty Patch
ID: 5132, title: Shard
ID: 5130, title: Orbit Snow
ID: 5162, title: Cone
ID: 2438, title: X Table
ID: 5085, title: Hank Sauce
ID: 5091, title: Tembea Canvas Tarp
ID: 5080, title: As Little Design as Possible
ID: 5023, title: Braun BN10
ID: 5028, title: Leatherman Black Oxide
ID: 5061, title: The Lucy Chair
ID: 5016, title: Mod Tablet
ID: 5033, title: The Wild
ID: 5003, title: Byrd Fins Pocket Comb
ID: 4998, title: Aurora Fire Starter
ID: 4988, title: Shinola Screwdrivers
ID: 4984, title: Binchotan Toothbrush
ID: 4980, title: The Forecast
ID: 4974, title: Shelve
ID: 4251, title: Infrared Electric Heater
ID: 4958, title: Brass Planter
ID: 4878, title: Grovemade Sleeve
ID: 4949, title: Kastrup
ID: 4943, title: Trvr Tote
ID: 4929, title: Short Tumbler
ID: 4920, title: Gfeller Document Case
ID: 4917, title: SoSo Wall Clock
ID: 4910, title: Bindery Memo Block
ID: 4891, title: Hex Opener
ID: 4886, title: Azmaya Oak Trays
ID: 4880, title: Stock S001
ID: 4873, title: Grovemade Mouse Pad
ID: 4863, title: Heather Charcoal Hoodie
ID: 4104, title: Concept: Neue Werkstatt Speaker
ID: 4851, title: Black Salad Bowl
ID: 4787, title: Magnifier
ID: 4836, title: Octahedron Ring Planter
ID: 4832, title: Barber Erasers
ID: 4819, title: All Black Everything Collection
ID: 4809, title: World Clock
Here's a runnable project, if you want to play around with it.
alex over 7 years ago
Not quite what I'm after, but thanks!
Halvo over 7 years ago