CustomCase CustomCase - 11 months ago 77
iOS Question

How do I fetch data from URL, using xcode 4.3.1 with NSJSONSerialization Class Reference

I am trying to get my head around the NSJSONSerialization Class Reference. In the lack of a code-example at the website, I´m lost.
There are millions of examples all around the web with other json libaries, but I haven´t been able to get any of them to work with the latest build of xcode. (I´m running: Version 4.3.1 (4E1019) and testing on iPhone 5.0.1)

I want to fetch the data from the json file into my iphone using a button.

Lets say I get my data from the URL:
http://companyurl/jsonfile.json (standard JSON-format)

The jsonfile.json looks somthing like this…;

"company":"Companyname 1",
"category":"category 1",
"company":"Companyname 2",
"category":"category 2",
"company":"Companyname 3",
"category":"category 3",

What do I write in my .h, and my .m file?

Thanks for any help! :)


Thanks guys. I figured it out. (...and here is what I did:)

In my .m file I added this code:

    - (IBAction)getDataFromJson:(id)sender {
        NSURL *url = [NSURL URLWithString:@""];

        NSData *jsonData = [NSData dataWithContentsOfURL:url];

        if(jsonData != nil)
            NSError *error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
            if (error == nil)
                NSLog(@"%@", result);

In my .h file, I added this code:

@interface ViewController : UIViewController
- (IBAction)getDataFromJson:(id)sender;