ios - 使用 JSON 解析指定的 Twitter 提要

标签 ios json twitter ios7.1 sttwitter

我目前正在制作一个应用程序,我想在其中的 TableView 中显示公司的 Twitter 提要。我创建了一个 TableView(如下所示,并将其链接到我的代码。我现在面临的问题是预定义推特用户、获取提要和解析数据。我已经接近通过 STTwitter API 获取推特提要以及消费者 key 和消费者 secret 。但是,我收到 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
         }
     }];
}

enter image description here

最佳答案

您不需要预先定义 Twitter 帐户。

您应该使用“仅限应用程序”模式。

你只需要 a couple of lines与 STTwitter:

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

[twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {

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

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

然后,当您获得状态时,用它们填充您的 tableView 的数据源,并重新加载表格。

关于ios - 使用 JSON 解析指定的 Twitter 提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23416638/

相关文章:

Twitter api 版本 2 引发客户端禁止错误

python - 使用 Twython 流获取坐标和地名

javascript - 使用 jQuery 将推文按钮加载到容器中

ios - UICollectionView RTL 方向

ios - 如何制作自定义对象的 NSMutableArray 属性的深拷贝

javascript - Highcharts:显示峰值

java - Json文件无法读取

mysql - 如何使用 MySQL 数据库中的值填充 Sencha Touch 2 中的列表

ios - Objective c-Symbolication 问题 Error : "DEVELOPER_DIR" is not defined at ./symbolicatecrash line 60

ios - 如何在 Facebook iOS SDK 中发布或分享?