AFNetworking 2.0解析的数据未在表格视图中显示

时间:2014-04-06 18:29:56

标签: ios json uitableview afnetworking-2

我的问题:表中没有数据显示。

下面是用于检索json对象数组并使用AFNetworking 2.0解析它的代码。我有一个UIViewController,我在其中放置了一个带有重用标识符EventCell的原型单元的tableview。我想要的只是在每个单元格中显示标题和图像。我在运行时没有错误。

的NSDictionary + events.h

#import <Foundation/Foundation.h>

@interface NSDictionary (events)

- (NSString *)eventImage;
- (NSString *)eventTitle;
- (NSDate *)eventDate;
- (NSNumber *)eventPrice;
- (NSNumber *)eventTicketsTotal;
@end

的NSDictionary + events.m

#import "NSDictionary+events.h"

@implementation NSDictionary (events)



- (NSString *)eventImage
{
    return self[@"event_image"];

}

- (NSString *)eventTitle
{
    return self[@"event_title"];

}

- (NSDate *)eventDate
{
    //    NSString *dateStr = self[@"date"]; // date = "2013-01-15";
    return [NSDate date];
}

- (NSNumber *)eventPrice
{
    NSString *cc = self[@"event_price"];
    NSNumber *n = @([cc intValue]);
    return n;
}

- (NSNumber *)eventTicketsTotal{
    NSString *cc = self[@"event_tickets_total"];
    NSNumber *n = @([cc intValue]);
    return n;
}

@end

的NSDictionary + events_package.h

#import <Foundation/Foundation.h>

@interface NSDictionary (NSDictionary_events_package)

-(NSArray *)upcomingWeather;
@end

的NSDictionary + events_package.m

#import "NSDictionary+events_package.h"

@implementation NSDictionary (NSDictionary_events_package)


- (NSArray *)upcomingWeather
{
    NSDictionary *dict = self[@"data"];
    return dict[@"events"];
}
@end

TDViewController.h

#import <UIKit/UIKit.h>
#import "NSDictionary+events.h"

@interface TDViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain) UITableView *tableView;
@end

TDViewController.m

#import "TDViewController.h"

#import "UIImageView+AFNetworking.h"
#import "TDSecondViewController.h"
#import "NSDictionary+events_package.h"

static NSString * const BaseURLString = @"http://xx.zzz.yy.xx/test/";

@interface TDViewController ()

@property(strong) NSDictionary *events;

@end

@implementation TDViewController   

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 1
    NSString *string = [NSString stringWithFormat:@"%@event_json.php?format=json", BaseURLString];
    NSLog(@"web service address: %@", string);

    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 2
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 3
        self.events = (NSDictionary *)responseObject;
        NSLog(@"%@", responseObject);
        self.title = @"JSON Retrieved";

        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        // 4
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Events"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];

    // 5
    [operation start];

}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"WeatherDetailSegue"]){
        UITableViewCell *cell = (UITableViewCell *)sender;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

        TDSecondViewController *wac = (TDSecondViewController *)segue.destinationViewController;

        NSDictionary *w;
        if (indexPath.section == 0) {
            {
                w = [self.events upcomingWeather][indexPath.row];
                //NSLog( @"this is w: %@", w );
            }
            wac.weatherDictionary = w;

        }
    }
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(!self.events)
        return 0;

    NSArray *upcomingWeather = [self.events upcomingWeather];
    return [upcomingWeather count];
    NSLog( @"the count is %lu", (long)[upcomingWeather count]);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"EventCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSDictionary *daysWeather = nil;


    NSArray *upcomingWeather = [self.events upcomingWeather];
    daysWeather = upcomingWeather[indexPath.row];
    NSLog( @"this is daysWeather: %@", daysWeather );
    cell.textLabel.text = [daysWeather eventTitle];
     NSLog(@"The content of arry is%@",daysWeather);

    NSURL *url = [NSURL URLWithString:daysWeather.eventImage];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    UIImage *placeholderImage = [UIImage imageNamed:@"placeholder"];

    __weak UITableViewCell *weakCell = cell;

    [cell.imageView setImageWithURLRequest:request
                          placeholderImage:placeholderImage
                                   success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                                       weakCell.imageView.image = image;
                                       [weakCell setNeedsLayout];

                                   } failure:nil];    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
}

@end

下面是我在模拟器上运行项目时得到的nslog输出(注意并非所有的nslog语句都在显示)。

2014-04-06 21:47:04.592 iCLUB[9198:60b] webservice address:     
http://xx.zzz.yy.xx/test/event_json.php?format=json
2014-04-06 21:47:04.685 iCLUB[9198:60b] {
data =     {
    events =         (
                    {
            "event_date" = "7-5-2014";
            "event_id" = 22;
            "event_image" = "http://xx.zzz.yy.xx/...";
            "event_price" = 150;
            "event_tickets_total" = 200;
            "event_title" = "New Event Title";
        },
                    {
            "event_date" = "3-2-2014";
            "event_id" = 23;
            "event_image" = "http://xx.zzz.yy.xx/...";
            "event_price" = 150;
            "event_tickets_total" = 200;
            "event_title" = "New Event Title 2";
        },
                    {
            "event_date" = "9-25-2014";
            "event_id" = 24;
            "event_image" = "http://xx.zzz.yy.xx/...";
            "event_price" = 150;
            "event_tickets_total" = 200;
            "event_title" = "New Event Title 33";
        }
    );
};
}

我无法理解问题所在,应用程序在模拟器上构建并运行,但单元格显示为完全空白。我非常感谢任何帮助。谢谢,JT。

4 个答案:

答案 0 :(得分:1)

问题的可能来源包括:

  • 无法为表格视图连接IBOutlet。如果tableView属性未正确连接,则它将为nil,因此[self.tableView reloadData]将不执行任何操作(因为向nil对象发送消息不会执行任何操作)。

    坦率地说,我不清楚这个tableView属性是如何设置的,因为它缺少在Interface Builder中连接控件时使用的典型IBOutlet限定条件,而且我没有看到你以编程方式设置它,任

  • 未能将视图控制器指定为delegate,更重要的是,指定了表视图的dataSource。如果是这种情况,即使您成功调用[self.tableView reloadData],也不会导致调用UITableViewDataSource方法。

我建议检查self.tableViewself.tableView.dataSource是否为非nil

答案 1 :(得分:0)

  1. 不会调用numberOfRowsInSection中的NSLog语句,因为该方法在语句之前返回!

        return [upcomingWeather count];
        NSLog( @"the count is %lu", (long)[upcomingWeather count]);
    
  2. 似乎没有调用cellForRowAtIndexPath,这可能是由于各种原因造成的,包括UITableView数据源和委托未设置,numberOfRowsInSection返回0,或者TableView为nil。使用调试器将允许您查看发生了哪些情况。

    查看Apple的resources进行调试。

答案 2 :(得分:0)

解析json数据时,请使用上面的代码

NSDictionary *dict = (NSDictionary *)responseObject;
    self.events = [dict objectForKey:@"data"];

答案 3 :(得分:0)

您是否记得为self.tableView设置委托和dataSource?当你不是UITableViewController的子类时,它不会自动完成。

我相信您从API获取的JSON无效。 events数组应括在括号[]中,而不是括号。此外,JSON不使用分号。请参阅JSON spec