2012-08-04 27 views
0

我刚刚使用this answer来设置Yahoo Finance的数据请求。如果您查看帖子,您会看到它会返回一个数据字典(本例中为出价)和密钥(符号)。只是为了测试它,我用这个代码,但它继续崩溃:如何使用来自YQL库存数据的JSON请求?

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

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

你能指出我做错了什么吗?我需要得到一个包含我要求的符号数据的字符串。

请注意:我的代码使用的是本文所基于的代码,即this

+0

尝试使用最少两个代码而不是一个。 – Rick 2012-08-10 07:40:58

回答

1

您喜欢的代码对从API返回的JSON数据的形状做出错误的假设,并且您得到了标准的KVC错误。 reason: '[<__NSCFString 0x7685930> valueForUndefinedKey:]: this class is not key value coding-compliant for the key BidRealtime.'

有了一些调试我得到它的工作...

根据您的输入数组,并通过稍微修改的功能链接过多,你需要访问该帖像这样:

#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; 
} 

你我会注意到我在这里发布的代码和你链接的函数之间的差异是quoteEntry的最终解析。我使用了一些断点来计算它在做什么,特别是在所有例外情况下,这些都导致了我的确切路线。

+0

你的方法似乎是返回一个NULL对象数组。我使用的方法我得到了工作,但只是有时,所以我想用你的方式。你能告诉我一个使用这种方法的例子吗? – 2012-08-16 16:23:55

+0

其实我觉得我能工作,谢谢! – 2012-08-16 16:37:16

0

所有你需要做的就是初始化NSMutableDictionary!

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

顺便说一句,上面的人完全不使用引号字典。直接返回quoteEntry。跳过一步。 :)

相关问题