【发布时间】:2012-12-21 16:48:15
【问题描述】:
我正在尝试解析来自 this URL 的 JSON,这是来自 Wordpress 的 JSON 输出。由于某种原因,UITableView 中没有输出。
这是我必须解析的代码。我确定我错过了一些东西,但我无法弄清楚如何在这段代码中解析嵌套的 JSON。
ViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"News";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:@"http://www.karthikk.net/?json=1"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
[mainTableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
}
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"title"];
cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"date"];
return cell;
}
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UITableView *mainTableView;
NSArray *news;
NSMutableData *data;
}
@end
请帮我解决这个问题。
非常感谢!我试过在 Stackoverflow 上引用多个线程,但都没有为我工作。
P.S.:我是 iOS 应用开发的新手。我正在使用this Video tutorial 来弄乱代码。
【问题讨论】:
-
如果您遇到任何错误怎么办?在不知道您的头文件是什么样子的情况下,很难仅复制/粘贴您的代码并查看发生了什么。
-
这样做:NSLog(@"news = %@", [news description]);在您将 news 分配给 JSON 值并发布结果之后(如果结果很大,请发布前几个对象)
-
我已经用头文件更新了问题。还有@ElJay,我该怎么做?你能帮忙吗?
标签: objective-c ios json wordpress