I am trying to pass data to labels from my JSON file onto a simple ViewController but I don't know where to actually pass that data. Would I be able to just add to my setDataToJson
method or would I add the data in my viewDidLoad
method?
here is my code
@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONString:(NSString*)fileLocation;
@end
@implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONString:(NSString*)fileLocation{
NSData* data = [NSData dataWithContentsOfFile:fileLocation];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end
@implementation ViewController
@synthesize name;
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(void)setDataToJson{
NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:@"Test.json"];
name.text = [infomation objectForKey:@"AnimalName"];//does not pass data
}
The problem is the way you're trying to retrieve your file. In order to do it right, you should find first its path in the bundle. Try something like this:
After doing that and once your view is loaded, you should be able to set your labels by retrieving the json like this:
It should be
valueForKey
instead.Example: