没有从Web服务获取数据

时间:2012-11-06 20:01:01

标签: iphone ios xcode

我刚接触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"];
}

1 个答案:

答案 0 :(得分:1)

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

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

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