将Twitter公共提要作为JSON获取

作为我项目的一部分,我需要在iOS应用中显示推文列表。 我尝试使用下面的代码,但它返回了JSON。 相同的代码适用于版本1.现在twitter api版本是1.1,另一个警告我得到了TWRequest is deprecated 。 这个弃用不是问题,即使我对SLRequest也有同样的SLRequest 。 这里我的问题是我需要在没有身份validation或身份validation的情况下获取特定用户推文的JSON

 TWRequest *postequest=[[TWRequest alloc]initWithURL:[NSURL URLWithString:@"https://api.twitter.com/1.0/statuses/user_timeline.json?screen_name=coolCracker&count=2"] parameters:nil requestMethod:TWRequestMethodGET]; [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { NSString *output; if ([urlResponse statusCode]==200) { NSError *err; NSDictionary *PublicTimeline=[NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err]; output=[NSString stringWithFormat:@"HTTP response status: %li\nPublic timeline:\n%@",(long)[urlResponse statusCode],PublicTimeline]; } else { output=[NSString stringWithFormat:@"No feed HTTP response was: %li\n",(long)[urlResponse statusCode]]; } [self performSelectorOnMainThread:@selector(displayResults:) withObject:output waitUntilDone:NO]; }]; -(void)displayResults:(NSString *)text { NSLog(@"tweets feed %@",text); } 

我在工作中使用了它,效果很好。 使用STTwitter。 在这里下载STTwitter文件。

将其放在您的视图didload中:

  STTwitterAPI *twitter = [STTwitterAPI twitterAPIAppOnlyWithConsumerKey:@"your consumer key" consumerSecret:@"your secret key"]; [twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) { [twitter getUserTimelineWithScreenName:@"your twitter account name" successBlock:^(NSArray *statuses) { self.twitterFeedList = [NSMutableArray arrayWithArray:statuses]; [self->listView reloadData]; } errorBlock:^(NSError *error) { NSLog(@"%@", error.debugDescription); }]; } errorBlock:^(NSError *error) { NSLog(@"%@", error.debugDescription); }]; 

嗨以下代码对我有用。 虽然TWRequest已被弃用,但它目前仍然有效。 稍后您可以将其更改为SLRequest。

 ACAccountStore *accountStore = [[ACAccountStore alloc] init]; ACAccountType *twitterType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; // Request access from the user to use their Twitter accounts. [accountStore requestAccessToAccountsWithType:twitterType options:nil completion:^(BOOL granted, NSError *error) { if (granted == YES){ //get accounts to use. NSArray *accounts = [accountStore accountsWithAccountType:twitterType]; if ([accounts count] > 0) { NSLog(@"account: %@", accounts); ACAccount *loggedinaccount; loggedinaccount = accounts[0]; // get tweets TWRequest *postRequest=[[TWRequest alloc]initWithURL:[NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=HuntEthane&count=2"] parameters:nil requestMethod:TWRequestMethodGET]; [postRequest setAccount:loggedinaccount]; [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { NSString *output; if ([urlResponse statusCode]==200) { NSError *err; NSDictionary *PublicTimeline=[NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err]; output=[NSString stringWithFormat:@"HTTP response status: %li\nPublic timeline:\n%@",(long)[urlResponse statusCode],PublicTimeline]; } else { output=[NSString stringWithFormat:@"No feed HTTP response was: %li\n",(long)[urlResponse statusCode]]; } [self performSelectorOnMainThread:@selector(displayResults:) withObject:output waitUntilDone:NO]; }]; } }else{ // show alert to inser user_name and password to login on twitter UIAlertView *alertTwitterAccount = [[UIAlertView alloc] initWithTitle:@"Enter with your twitter account" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Login", nil]; [alertTwitterAccount setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput]; [[alertTwitterAccount textFieldAtIndex:0] setPlaceholder:@"User"]; [alertTwitterAccount setDelegate:self]; [alertTwitterAccount setTag:1]; [alertTwitterAccount show]; } }]; 

请记住添加以下框架以使此代码有效。

  • Twitter.FrameWork
  • Social.FrameWork
  • Accounts.Framework
  • Security.FrameWork

    如果要使用SLRequest而不是TWRequest ,请将request语句替换为以下语句

    SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=HuntEthane&count=2"]parameters:nil];

前进最简单的方法是采用Tweeter的Fabric.io ,因为开发平台包含Tweeter嵌入 : https : //get.fabric.io/native-social

“将Twitter内容引入您应用的最简单方法。”

老实说,我没有考虑Fabric.io所需的身份validation部分。

否则,您需要遵守并尊重访问Twitter REST APIStreaming API的规则,两者都有详细记录。 OAuth身份validation是必需的。

如果您希望避免在应用程序中进行身份validation,您可以编写一个简单的Web REST API来处理身份validation并向您的iOS应用程序提供(选择)推文。

  1. 首先,您需要在Twitter上注册一个应用程序
  2. 记下您的消费者密钥消费者秘密
  3. 用您选择的语言编写一个简单的服务器API(代理)。

我个人更喜欢Node.js上的 JavaScript 。 考虑在npm上使用像express.jsoauth这样的库,但是你可以在npm中搜索任何其他实现的Twitter代理/ API。 代码主要包括获取OAuth访问令牌,然后调用选定的Twitter API,并通过缓存结果来尊重速率限制。