我正在尝试从此URL解析 JSON ,这是 Wordpress 的 JSON 输出。由于某种原因,UITableView 中没有输出。
这是我必须解析的代码。我确定我错过了一些东西,但我无法弄清楚如何在这段代码中解析嵌套的 JSON。
视图控制器.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;
}
视图控制器.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UITableView *mainTableView;
NSArray *news;
NSMutableData *data;
}
@end
请帮我解决这个问题。
非常感谢!我试过在 Stackoverflow 上引用多个线程,但都没有为我工作。
PS:我是iOS应用开发的新手。我正在使用这个视频教程来弄乱代码。