我试图解析来自this URL的JSON,它是Wordpress的JSON输出。出于某种原因,UITableView中没有输出。将Wordpress JSON解析为iOS上的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 App开发的新手。我正在使用this Video tutorial来混淆代码。
如果出现任何错误,该怎么办?不知道你的头文件是什么样的,只是复制/粘贴你的代码并看看发生了什么是很困难的。 – propstm
这样做:NSLog(@“news =%@”,[news description]);在将新闻分配给JSON值之后并将结果发布(如果结果很大,请发布前几个对象) –
我已经用头文件更新了问题。和@ElJay,我该怎么做?能否请你帮忙? –