【问题标题】:How would I get the latest tweet from a user and update it it in a UILabel?我如何从用户那里获得最新的推文并在 UILabel 中更新它?
【发布时间】:2014-08-03 01:08:52
【问题描述】:

我正在尝试从一个 Twitter 帐户获取最新的推文,并在我的视图中以 UILabel 进行更新。推文应该存储在一个字符串中,并在每次有新推文可用时更新。我尝试使用带有“screen_name”和“count”参数的 twitter API,并将所有推文存储在一个数组中。当我打印数组时,它返回一个空值。任何帮助将不胜感激。

编辑: 我现在收到“错误的身份验证数据”错误。

    NSURL *requestAPI = [NSURL URLWithString:@"https://api.twitter.com/1.1/search/tweets.json"];

    NSDictionary *parameters = @{@"q": @"@user",
                                                 @"result_type":@"recent",
                                                 @"count": @"1"};

    SLRequest *posts = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestAPI parameters:parameters];

    [posts performRequestWithHandler:^(NSData *response, NSHTTPURLResponse *urlResponse, NSError *error){

        self.tweet = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"%@",self.tweet);
  }];

【问题讨论】:

  • 如果您不发布相关代码,任何人都无法提供帮助。解释代码在做什么和不做什么。在运行代码时提供有关变量值的详细信息。

标签: ios json twitter nsstring uilabel


【解决方案1】:

如果您想从某个特定用户那里获取推文,您可能应该使用 App Only Authentication(请参阅链接:https://dev.twitter.com/docs/auth/application-only-auth)。另外,我建议使用STTwitter 库来简化事情。见以下代码:

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

[twitter verifyCredentialsWithSuccessBlock:^(NSString *username) {

        [twitter getUserTimelineWithScreenName:@"thetwitteraccount" count:100 successBlock:^(NSArray *statuses) {

            self.tweets = [NSMutableArray arrayWithArray:statuses];

            //Say we want to access the text of the first tweet in the array
            NSDictionary *text = self.tweets[0];
            self.yourlabel.text = text[@"text"];

        } errorBlock:^(NSError *error) {
            code

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

【讨论】:

  • 这给了我一个数组。我需要一个字符串才能在 uilabel 中显示它。
  • 你可以创建一个 NSDictionary 来访问数组的索引并且只传递推文的文本。然后您可以将 label.text 设置为等于推文的文本。如果你使用 STTwitter 就很简单
猜你喜欢
  • 2011-08-10
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多