Я пытался добавить данные JSON с веб-сервера в tableviewcontroller. Это мой текущий код.JSON to Tableview
НСлог _datalist печатает JSON, но другие методы для фактического размещения данных в ячейках, не .. Код выглядит правильно, и поскольку _datalist NSarray фактически получает данные, я не уверен, как обрабатывайте это. Вот почему мне нужна ваша помощь и советы.
Что касается того, что я выяснил, метод, в котором ячейки инициализируются данными JSON, не может его извлечь или использовать. Я понял, что мне нужно кодировать входящие данные?
#import "TopUsersViewController.h"
@interface TopUsersViewController()
@property NSArray* dataList;
@end
@implementation TopUsersViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self readDataFromFile];
[self.tableView reloadData];
}
-(void)readDataFromFile
{
NSString *urlAsString = @"http://myURL.com/json.json";
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
NSLog(@"%@", urlAsString);
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (error)
{
// no internet/can't fetch!
NSLog(@"Failure %@",error.localizedDescription);
}
NSLog(@"Success!");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"works.");
self.dataList = (NSArray *)[NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
// this NSlog prints the JSON data successfully.
NSLog(@"oo%@ and array %@",_dataList,_array);
});
}];
}
// ни один из этих методов не работает ..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// count the initialized array from viewDidLoad
return self.dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"return the data");
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
id keyValuePair = self.dataList[indexPath.row];
cell.textLabel.text = keyValuePair[@"identity"];
cell.detailTextLabel.text=[NSString stringWithFormat:@"Points: %@", keyValuePair[@"points"]];
return cell;
}
@end
В следующий раз я рассмотрю другие вопросы, спасибо, что указали это! Счастливое кодирование! –
@SyedeHussaini Вам действительно нужно исправить проблемы в вашем ответе, если вы собираетесь указать на него другие. – rmaddy
Кроме того, ваша ссылка была сделана для Swift. Поскольку мое текущее приложение написано в Obj-c, оно не имеет значения. : P –