Помещение моего JSON в табличное представление - PullRequest
0 голосов
/ 12 марта 2012

то, что я сейчас пытаюсь сделать, это получить информацию о моем json (временную шкалу пользователя в твиттере) и вставить ее в таблицу, все в ней работает, но когда дело доходит до добавления информации в tableView, это не так что-нибудь об этом, вот мой код:

#import "FirstViewController.h"
#import <Twitter/Twitter.h>
#import <Accounts/Accounts.h>

@interface FirstViewController ()
- (void)fetchData;
@end

@implementation FirstViewController
@synthesize timelineTwiter = _timelineTwiter;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"First", @"First");
        self.tabBarItem.image = [UIImage imageNamed:@"first"];
    }
    return self;
}

-(void)fetchData {
    ACAccountStore *store = [[ACAccountStore alloc] init];
    ACAccountType *twitterAccountType = 
    [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    [store requestAccessToAccountsWithType:twitterAccountType 
                     withCompletionHandler:^(BOOL granted, NSError *error) {
                         if (!granted) {
                             NSLog(@"User rejected access to his account.");
                         } 
                         else {
                             NSArray *twitterAccounts = 
                             [store accountsWithAccountType:twitterAccountType];

                             if ([twitterAccounts count] > 0) {
                                 ACAccount *account = [twitterAccounts objectAtIndex:0];

                                 NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                                 [params setObject:@"1" forKey:@"include_entities"];

                                 NSURL *url = 
                                 [NSURL 
                                  URLWithString:@"http://api.twitter.com/1/statuses/home_timeline.json"];

                                 TWRequest *request = 
                                 [[TWRequest alloc] initWithURL:url 
                                                     parameters:params 
                                                  requestMethod:TWRequestMethodGET];

                                 [request setAccount:account];

                                 [request performRequestWithHandler:
                                  ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
                                      if (!responseData) {
                                          NSLog(@"%@", error);
                                      } 
                                      else {
                                          NSError *jsonError;
                                          NSArray *timeline = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&jsonError];
                                          self.timelineTwiter = timeline;
                                          if (timeline) {                          
                                              NSDictionary* tweets0 = [timeline objectAtIndex:0];
                                              NSLog(@"%@", [tweets0 objectForKey:@"text"]);
                                              NSLog(@"%@", [[tweets0 objectForKey:@"user"] objectForKey:@"screen_name"]);
                                              NSDictionary* tweets1 = [timeline objectAtIndex:1];
                                              NSLog(@"%@", [tweets1 objectForKey:@"text"]);
                                              NSLog(@"%@", [[tweets1 objectForKey:@"user"] objectForKey:@"screen_name"]);
                                              NSDictionary* tweets2 = [timeline objectAtIndex:2];
                                              NSLog(@"%@", [tweets2 objectForKey:@"text"]);
                                              NSLog(@"%@", [[tweets2 objectForKey:@"user"] objectForKey:@"screen_name"]);


                                          } 
                                          else { 
                                              NSLog(@"%@", jsonError);
                                          }
                                      }
                                  }];

                             } 
                         }  
                     }];

}

-(IBAction)refreshTimeline:(id)sender {
    [self fetchData];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.timelineTwiter count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    id userTimeline = [self.timelineTwiter objectAtIndex:[indexPath row]];
    cell.textLabel.text = [userTimeline objectForKey:@"text"];
    cell.detailTextLabel.text = [userTimeline valueForKeyPath:@"user.name"];


    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self fetchData];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewWillAppear:(BOOL)animated
{
    [self fetchData];
    [super viewWillAppear:animated];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

но он никогда не загружает данные в табличное представление, любая помощь?

Примечание:

Я использую его с интерфейсом конструктора.

& В идеале я хотел бы создать собственную ячейку, чтобы я мог разработать макет каждой ячейки, поэтому, если вы знаете о каких-либо хороших сайтах, которые покажут, как это сделать, это также будет большой рукой.

Ответы [ 2 ]

4 голосов
/ 12 марта 2012

Вы должны вернуть как минимум один раздел к таблице как минимум. прямо сейчас вы возвращаете ноль секций.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
2 голосов
/ 12 марта 2012

Вы пропустили reloadData в конце вашей fetchData реализации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...