0

我正在尝试从 api 获取数据,并且我有以下代码:

// 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);

我将如何连接到第 9 行?

4

2 回答 2

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.

于 2013-06-14T19:52:51.867 回答
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.

于 2013-06-14T19:52:35.050 回答