我試圖解析來自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,我該怎麼做?能否請你幫忙? –