Анализ указанной ленты Twitter с помощью JSON

В настоящее время я делаю приложение, в котором я хотел бы отображать канал Twitter компании в TableView. Я создал TableView (показан ниже, и я связал его со своим кодом. Проблема, с которой я столкнулся сейчас, заключается в предварительном определении пользователя Twitter, получении канала и анализе данных. Я приблизился к получению канала Twitter через STTwitter API, а также ключ потребителя и секрет потребителя. Однако я получаю ошибку аутентификации 401. Я нахожусь в потеря для подключения моей ленты, и я никогда не работал с JSON в моей жизни, так что это довольно сложная задача для меня.Помимо API, я пробовал код ниже, который приводит к пустому твиту.

#import "FeedController3.h"
#import "FeedCell3.h"
#import "FlatTheme.h"

@interface FeedController3 ()

@property (nonatomic, strong) NSArray* profileImages;

@end

@implementation FeedController3

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString* boldFontName = @"Avenir-Black";

    [self styleNavigationBarWithFontName:boldFontName];

    self.title = @"Twitter Feed";

    self.feedTableView.dataSource = self;
    self.feedTableView.delegate = self;

    self.feedTableView.backgroundColor = [UIColor whiteColor];
    self.feedTableView.separatorColor = [UIColor colorWithWhite:0.9 alpha:0.6];

    self.profileImages = [NSArray arrayWithObjects:@"profile.jpg", @"profile-1.jpg", @"profile-2.jpg", @"profile-3.jpg", nil];

    [self getTimeLine];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    //return _dataSource.count;
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
    FeedCell3* cell = [tableView dequeueReusableCellWithIdentifier:@"FeedCell3"];

    cell.nameLabel.text = @"Laura Leamington";
    cell.updateLabel.text = @"This is a pic I took while on holiday on Wales. The weather played along nicely which doesn't happen often";

    cell.dateLabel.text = @"1 hr ago";
    cell.likeCountLabel.text = @"293 likes";
    cell.commentCountLabel.text = @"55 comments";

    NSString* profileImageName = self.profileImages[indexPath.row%self.profileImages.count];
    cell.profileImageView.image = [UIImage imageNamed:profileImageName];

    return cell;
    */

    FeedCell3* cell = [tableView dequeueReusableCellWithIdentifier:@"FeedCell3"];

    NSDictionary *tweet = _dataSource[[indexPath row]];

    cell.nameLabel.text = @"<Company Name>";

    cell.updateLabel.text = tweet[@"text"];

    cell.dateLabel.text = @"1 hr ago";
    cell.likeCountLabel.text = @"293 likes";
    cell.commentCountLabel.text = @"55 comments";

    NSString* profileImageName = self.profileImages[indexPath.row%self.profileImages.count];
    cell.profileImageView.image = [UIImage imageNamed:profileImageName];

    return cell;


}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)styleNavigationBarWithFontName:(NSString*)navigationTitleFont{

    /*
    UIColor* color = [UIColor whiteColor];
    [FlatTheme styleNavigationBar:self.navigationController.navigationBar withFontName:navigationTitleFont andColor:color];
     */
    //[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:9.0f/255.0f green:49.0f/255.0f blue:102.0f/255.0f alpha:1.0f]];


    UIImageView* searchView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search.png"]];
    searchView.frame = CGRectMake(0, 0, 20, 20);

    UIBarButtonItem* searchItem = [[UIBarButtonItem alloc] initWithCustomView:searchView];

    self.navigationItem.rightBarButtonItem = searchItem;
    /*
    UIButton* menuButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 28, 20)];
    [menuButton setImage:[UIImage imageNamed:@"menu.png"] forState:UIControlStateNormal];
    [menuButton addTarget:self action:@selector(dismissView:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem* menuItem = [[UIBarButtonItem alloc] initWithCustomView:menuButton];
    self.navigationItem.leftBarButtonItem = menuItem;
     */
}

-(IBAction)dismissView:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getTimeLine {
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account
                                  accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [account requestAccessToAccountsWithType:accountType
                                     options:nil completion:^(BOOL granted, NSError *error)
     {
         if (granted == YES)
         {
             NSArray *arrayOfAccounts = [account
                                         accountsWithAccountType:accountType];

             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount =
                 [arrayOfAccounts lastObject];

                 NSURL *requestURL = [NSURL URLWithString:
                                      @"https://api.twitter.com/1.1/statuses/user_timeline.json"];

                 NSDictionary *parameters =
                 @{@"screen_name" : @"@RileyVLloyd",
                   @"include_rts" : @"0",
                   @"trim_user" : @"1",
                   @"count" : @"20"};

                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodGET
                                           URL:requestURL parameters:parameters];

                 postRequest.account = twitterAccount;

                 [postRequest performRequestWithHandler:
                  ^(NSData *responseData, NSHTTPURLResponse
                    *urlResponse, NSError *error)
                  {
                      self.dataSource = [NSJSONSerialization
                                         JSONObjectWithData:responseData
                                         options:NSJSONReadingMutableLeaves
                                         error:&error];

                      if (self.dataSource.count != 0) {
                          dispatch_async(dispatch_get_main_queue(), ^{
                              [self.feedTableView reloadData];
                          });
                      }
                  }];
             }
         } else {
             // Handle failure to get account access
         }
     }];
}

введите здесь описание изображения


person SuperAdmin    schedule 01.05.2014    source источник


Ответы (1)


Вам не нужно предварительно определять учетную запись Twitter.

Вы должны использовать режим «Только приложение».

Вам просто нужно пару строк с STTwitter:

STTwitterAPI *twitter = [STTwitterAPI twitterAPIAppOnlyWithConsumerKey:@""
                                                        consumerSecret:@""];

[twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {

    [twitter getUserTimelineWithScreenName:@"nike"
                              successBlock:^(NSArray *statuses) {
        // ...
    } errorBlock:^(NSError *error) {
        // ...
    }];

} errorBlock:^(NSError *error) {
    // ...
}];

Затем, когда вы получите статусы, заполните ими dataSource вашего tableView и перезагрузите таблицу.

person nst    schedule 05.05.2014