In order to test the JSON
handling of my app I have created a test.json file that I want to load into an UITableView
in my UIViewController
class. I have created the JSON
file and made a separate json loading class (JSONLoader
) that implements the code:
#import <Foundation/Foundation.h>
@interface JSONLoader : NSObject
//return an array of chat objects from the json file given by url
- (NSArray *)chattersFromJSONFile:(NSURL *)url;
@end
in the .h file, in the .m file I have:
#import "JSONLoader.h"
#import "Chatter.h"
@implementation JSONLoader
- (NSArray *)chattersFromJSONFile:(NSURL *)url {
//create a NSURLRequest with the given URL
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
//get data
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//create NSDictionary from the JSON data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//create new array to hold chatter information
NSMutableArray *localChatters = [[NSMutableArray alloc] init];
//get an Array of dictionaries with the key "chatters"
NSArray *chatterArray = [jsonDictionary objectForKey:@"chatters"];
//iterate through array of dictionaries
for(NSDictionary *dict in chatterArray) {
//create new chatter object for each one and initialize it with info from the dictionary
Chatter *chatter = [[Chatter alloc] initWithJSONDictionary:dict];
//add the chatter to an array
[localChatters addObject:chatter];
}
//return array
return localChatters;
}
@end
Which I believe will work for both a JSON
file loaded from a URL
(the end goal) and also a JSON
file I have in my Xcode project as a test. In the -viewDidLoad
of my viewController.m file I use:
//create a new JSONLoader with a local file from URL
JSONLoader *jsonLoader = [[JSONLoader alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"json"];
NSLog(@"%@",url);
//load the data on a background queue
//use for when connecting a real URL
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_localChatters = [jsonLoader chattersFromJSONFile:url];
NSLog(@"%@",_localChatters);
//push data on main thread (reload table view once JSON has arrived)
[self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
});
I import the JSONLoader
file and also the class the represents a test JSON
object (singular chatter) and in my implementation I declare a NSArray *_localChatters
.
I'm pretty convinced this should work, however when I NSLog(...)
the array it displays empty ()
, where it should have a list of class objects. This means the JSON
is never being parsed by my JSONLoader
in the first place.
Any particular reason this could happen?