简体   繁体   English

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

[英]AFNetworking 2.0 parsed data not displaying in table view

my issue: no data is displaying in the table. 我的问题:表格中没有数据。

below is the code being used to retrieve the json object array and parse it using AFNetworking 2.0. 以下是用于检索json对象数组并使用AFNetworking 2.0对其进行解析的代码。 I have a UIViewController where I placed a tableview with a prototype cell that has a reuse identifier EventCell. 我有一个UIViewController,在其中放置了带有原型单元的表格视图,原型单元具有重用标识符EventCell。 All I want is to display a title and an image in every cell. 我想要的是在每个单元格中显示标题和图像。 I get no errors at runtime. 我在运行时没有错误。

NSDictionary+events.h 的NSDictionary + events.h

#import <Foundation/Foundation.h>

@interface NSDictionary (events)

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

NSDictionary+events.m 的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 的NSDictionary + events_package.h

#import <Foundation/Foundation.h>

@interface NSDictionary (NSDictionary_events_package)

-(NSArray *)upcomingWeather;
@end

NSDictionary+events_package.m 的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 TDViewController.h

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

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

TDViewController.m 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

below is the nslog output I get when i run the project on the simulator (note not all of the nslog statements are displaying). 以下是我在模拟器上运行项目时获得的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";
        }
    );
};
}

I just can't catch what the issue is, the app builds and runs on the simulator, but the cells appear completely empty. 我只是不明白问题是什么,该应用程序在模拟器上构建并运行,但是单元格看上去完全是空的。 I would greatly appreciate any help. 我将不胜感激任何帮助。 Thanks, JT. 谢谢,JT。

Possible sources of the problem include: 该问题的可能原因包括:

  • Failure to connect the IBOutlet for the table view. 未能为表视图连接IBOutlet If the tableView property is not hooked up properly, it would be nil , and thus [self.tableView reloadData] would do nothing (because sending a message to a nil object does nothing). 如果未正确连接tableView属性,则它将为nil ,因此[self.tableView reloadData]将不执行任何操作(因为向nil对象发送消息不会执行任何操作)。

    Frankly, I'm unclear how this tableView property is getting set, because it lacks the typical IBOutlet qualification used when connecting controls in Interface Builder and I don't see you setting it programmatically, either. 坦率地说,我不清楚如何设置此tableView属性,因为它缺乏在Interface Builder中连接控件时使用的典型IBOutlet限定,而且我也看不到您以编程方式进行设置。

  • Failure to specify your view controller as the delegate and, more importantly, the dataSource of the table view. 无法将视图控制器指定为delegate ,更重要的是,未指定表视图的dataSource If this is the case, even if you successfully called [self.tableView reloadData] , it would not result in the UITableViewDataSource methods being called). 如果是这种情况,即使您成功调用了[self.tableView reloadData] ,也不会导致调用UITableViewDataSource方法。

I'd suggest checking that self.tableView and self.tableView.dataSource are non- nil . 我建议检查一下self.tableViewself.tableView.dataSource是否为nil

  1. This NSLog statement in numberOfRowsInSection won't ever be called because the method returns before the statement! 不会调用numberOfRowsInSection中的此NSLog语句,因为该方法在该语句之前返回!

      return [upcomingWeather count]; NSLog( @"the count is %lu", (long)[upcomingWeather count]); 
  2. It seems like cellForRowAtIndexPath is not getting called, which can be due to various reasons including the UITableView datasource and delegate not being set, numberOfRowsInSection returning 0, or your TableView being nil. 似乎没有调用cellForRowAtIndexPath,这可能是由于多种原因造成的,包括未设置UITableView数据源和委托,numberOfRowsInSection返回0或TableView为零。 Using the debugger will allow you to see which of these scenarios is happening. 使用调试器将使您看到正在发生哪种情况。

    Check out Apple's resources on debugging. 查看苹果的调试资源

When you parse json data , use above code 当解析json数据时,请使用上面的代码

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

Did you remember to set the delegate and dataSource for self.tableView? 您还记得为self.tableView设置委托和数据源吗? It's not done for you automatically when you don't subclass UITableViewController. 当您不继承UITableViewController的子类时,它不会自动为您完成。

I believe the JSON you're getting from the API is invalid. 我认为您从API获取的JSON无效。 The Array of events should be enclosed in brackets [] not parentheses. events数组应括在方括号[]而不是括号中。 Additionally, JSON doesn't use semicolons. 此外,JSON不使用分号。 See the JSON spec . 请参阅JSON 规范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM