Question

When I call [NSArray arrayWithContentsOfFile:], I get nil.

NSURL *fileURL = [NSURL URLWithString:className relativeToURL:[self JSONDataRecordsDirectory]];
return [NSArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@", [fileURL path]]];

Alternatively, I also get nil when I call:

[NSArray arrayWithContentsOfURL:]

The results of all my files are in JSON here: https://gist.github.com/neverbendeasy/03d047a6789b0ae14e1f

When I check the fileURLs, the data is there.

What am I missing?

Was it helpful?

Solution

You can't load a JSON file using NSArray arrayWith.... That method can only load a plist file with an array as the root.

If your file is a JSON file you should use:

NSData *jsonData = [NSData dataWithContentsOfURL:fileURL];
NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonArray) {
    // do something with jsonArray
} else {
    NSLog(@"Couldn't load JSON from %@: %@", fileURL, error);
}

This assumes the top level of the JSON file is an array.

OTHER TIPS

Use NSURL's

+ (id)fileURLWithPath:(NSString *)path

or

+ (id)fileURLWithPath:(NSString *)path isDirectory:(BOOL)isDir

instead of

+ (id)URLWithString:(NSString *)URLString

when working with the local filesystem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top