0

I am trying to fetch data from an api and I have this code:

// create the URL we'd like to query
NSString *urlString = [NSString stringWithFormat:@"https://www.googleapis.com/adsense/v1.1/reports"];
NSString *token = auth.accessToken;
NSMutableURLRequest *myURL = [NSURL URLWithString:urlString];
[myURL addValue:token forHTTPHeaderField:@"Authentication"];

// we'll receive raw data so we'll create an NSData Object with it
@@@@@@
How would I complete this step? So far I have 
    NSData *myData = 
@@@@@@

// now we'll parse our data using NSJSONSerialization
id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];

// typecast an array and list its contents
NSArray *jsonArray = (NSArray *)myJSON;

NSLog(@"%@", jsonArray);

How would I connect on the 9th line?

StackOverflower
  • 1,031
  • 2
  • 12
  • 21

2 Answers2

1

It looks like you are putting all this code in one place (making a synchronous network request). This is typically a bad idea. You should put the first part (creating and starting the request) in one place, and put the parsing code in a separate method / block that gets called once the request is completed. (This is called an asynchronous network request.)

You should take a look at +[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]. You can pass your NSURLRequest in here, and then specify the completion (parsing, etc.) in the completion handler. It will give you the NSData object you're looking for - see documentation here.

If you have more than a handful of network connections, this can get unwieldy. You may want to look at a third party library like AFNetworking, which can manage much of the tedious stuff for you, and let you focus on calling a URL, and parsing the response.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
0

You need:

NSData *myData = [NSURLConnection sendSynchronousRequest:myURL returningResponse:nil error:nil];

This is a synchronous call. I'll suggest always using asynchronous webcalls is a good way.

Midhun MP
  • 103,496
  • 31
  • 153
  • 200