0

我是 iphone 开发新手,我想使用 JSON 解析从 Web 服务获取数据这里是代码

-(void)loadDataSource

  {

   NSString *URLPath = [NSString stringWithFormat:@"https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=Official%20Google%20Blogs"];


  NSURL *URL = [NSURL URLWithString:URLPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];


 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];

    if (!error)// && responseCode == 200)
    {
        id res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        if (res && [res isKindOfClass:[NSDictionary class]])
        {

           self.dict=[res objectForKey:@"responseData"];  
          self.items = [self.dict objectForKey:@"entries"];
            [self dataSourceDidLoad];
        } 
        else 
        {
            [self dataSourceDidError];
        }
    } 
    else 
    {
        [self dataSourceDidError];
    }
}];

}

当我运行此代码时,它什么也不显示,并且索引处的集合视图的代码是

- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView viewAtIndex:(NSInteger)index 

{

NSDictionary *item = [self.items objectAtIndex:index];

PSBroView *v = (PSBroView *)[self.collectionView dequeueReusableView];
if (!v) 
{
    v = [[PSBroView alloc] initWithFrame:CGRectZero];
}

[v fillViewWithObject:item];

return v;

}

在 fillViewWithObject 的代码下方

- (void)fillViewWithObject:(id)object
{
[super fillViewWithObject:object];

self.captionLabel.text = [object objectForKey:@"title"];
}
4

1 回答 1

1

你显然没有检查你的错误,因为当我运行这个时,我得到“错误的 URL”作为错误。我还收到一个编译器警告,“转换率比参数多”。那是因为 % 在您的 url 字符串中。您不应该使用 stringWithFormat - 只需传递文字字符串,它应该可以工作:

NSString *URLPath = @"https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=Official%20Google%20Blogs";

我经常看到这个错误(或只是浪费代码)。除非您提供格式字符串和参数,否则不应使用 stringWithFormat。

于 2012-11-06T21:00:50.077 回答