Redneys
Redneys

Reputation: 305

How to use JSON request from YQL stock data?

I just used this answer to set up a data request from Yahoo Finance. If you take a look at the post, you'll see it returns a dictionary of data (in this case, bids) and keys (symbols). Just to test it, I used this code, but it continues to crash:

NSArray *tickerArray = [[NSArray alloc] initWithObjects:@"AAPL", nil];
NSDictionary *quotes = [self fetchQuotesFor:tickerArray];

NSLog(@"%@",[quotes valueForKey:@"AAPL"]);

Can you point out what I'm doing wrong? I need to get a string containing the data for the symbols I ask for.

PLEASE NOTE:My code is using the code that this post was based on, i.e. this.

Upvotes: 0

Views: 1851

Answers (2)

KD24
KD24

Reputation: 1

All you have to do is initialize the NSMutableDictionary!

NSMutableDictionary *quotes = [[NSMutableDictionary alloc] init];

BTW the guy above is totally NOT making use of the quotes dict. straight up returning the quoteEntry. Skipping one step. :)

Upvotes: 0

Jessedc
Jessedc

Reputation: 12460

The code you liked to is making the wrong assumption about the shape of the JSON data coming back from the API and you're getting a standard KVC error. reason: '[<__NSCFString 0x7685930> valueForUndefinedKey:]: this class is not key value coding-compliant for the key BidRealtime.'

With some debugging I got it working...

Based on your input array and by slightly modifying the function linked too, you need to access the quote like so:

#define QUOTE_QUERY_PREFIX @"http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20BidRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("
#define QUOTE_QUERY_SUFFIX @")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="

+ (NSDictionary *)fetchQuotesFor:(NSArray *)tickers {
  NSMutableDictionary *quotes;

  if (tickers && [tickers count] > 0) {
    NSMutableString *query = [[NSMutableString alloc] init];
    [query appendString:QUOTE_QUERY_PREFIX];

    for (int i = 0; i < [tickers count]; i++) {
      NSString *ticker = [tickers objectAtIndex:i];
      [query appendFormat:@"%%22%@%%22", ticker];
      if (i != [tickers count] - 1) [query appendString:@"%2C"];
    }

    [query appendString:QUOTE_QUERY_SUFFIX];

    NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil] : nil;

    NSDictionary *quoteEntry = [results valueForKeyPath:@"query.results.quote"];
    return quoteEntry;
  }
  return quotes;
}

You'll notice the difference between the code I've posted here and the function you linked too is the final parsing of quoteEntry. I worked out what it was doing with some breakpoints, specifically on all exceptions that lead me to the exact line.

Upvotes: 1

Related Questions