Iam是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"];
}
最佳答案
您显然没有检查您的错误,因为当我运行此错误时,我得到“错误的URL”作为错误。我还收到一个编译器警告,“%的转换多于参数”。这是因为您的网址字符串中包含%。您不应该使用stringWithFormat-只需传递文字字符串,它就可以工作:
NSString *URLPath = @"https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=Official%20Google%20Blogs";
我经常看到此错误(或只是浪费的代码)。除非要提供格式字符串和参数,否则不应使用stringWithFormat。
关于iphone - 无法从Web服务获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13258476/