【问题标题】:How do you get the "images" from a twitter feed to show in an iOS app如何从 twitter 提要中获取“图像”以显示在 iOS 应用程序中
【发布时间】:2015-07-26 07:28:26
【问题描述】:

我有一个访问 Twitter 提要并将文本放入表格的代码。然后我编辑了代码,这样我就可以在单独的视图中以我的自定义方式显示文本,但我也想从推文中抓取图像,尽管搜索了一个多小时,但还是找不到一个参考。我已经看到了如何“发布”图像,但为了清楚起见,我需要从相关推文中获取并“显示”图像。

以下是我处理 Twitter 访问的代码中的亮点:

-(void)twitterTimeLine
{
    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];   // last account on list of accounts
                NSURL *requestAPI = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json"];


                NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];

                [parameters setObject:@"30" forKey:@"count"];

                [parameters setObject:@"1" forKey:@"incude_entities"];

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

                posts.account = twitterAccount;

                [posts performRequestWithHandler:^(NSData *response, NSHTTPURLResponse *urlResponse, NSError *error) {
                    if (response)
                    {
                        // TODO: might want to check urlResponse.statusCode to stop early
                        NSError *jsonError;  // use new instance here, you don't want to overwrite the error you got from the SLRequest
                        NSArray *array =[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&jsonError];
                        if (array) {
                            if ([array isKindOfClass:[NSArray class]]) {
                                self.array = array;
                                NSLog(@"resulted array: %@",self.array);
                            }
                            else {
                                // This should never happen
                                NSLog(@"Not an array! %@ - %@", NSStringFromClass([array class]), array);
                            }
                        }
                        else {
                            // TODO: Handle error in release version, don't just dump out this information
                            NSLog(@"JSON Error %@", jsonError);
                            NSString *dataString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
                            NSLog(@"Received data: %@", dataString ? dataString : response);    // print string representation if response is a string, or print the raw data object
                        }
                    }
                    else {
                        // TODO: show error information to user if request failed
                        NSLog(@"request failed %@", error);
                    }

                    self.array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

                    if (self.array.count != 0)
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.tableView reloadData];    // this part loads into table - important!
                        });

                    }
                }];
            }
        }
        else
        {
            NSLog(@"%@", [error localizedDescription]);
        }

    }];
}

这是我显示推文的方式

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    NSDictionary *tweet = _array[indexPath.row];

    cell.textLabel.text = tweet[@"text"];
    //NSString *element = [myArray objectAtIndex:2];
    //NSString *element = myArray[2];


// I created some custom views to show the text, but kept the table for testing purposes
    TemplateView *tempView = [viewArray objectAtIndex:testCounter];
    tempView.TweetView.text = tweet[@"text"];
    // -> this was what I was hoping for // tempView.ContentView.image = tweet[@"image"];
    testCounter++;
    if (testCounter >= 30)
    {
        testCounter = 0;
    }

    return cell;
}

我取出了我认为需要查看的关键行:

tempView.TweetView.text = tweet[@"text"];
tempView.ContentView.image = tweet[@"image"];

//希望后者能像第一个那样工作,但显然没那么简单

这可能是不可能的,如果是这样,我将如何从“链接”(url)获取图像并确保它是图像而不是视频或其他网站?

我可以设置一个“单词搜索”来从推文中获取以 http 开头的文本,并希望从字符串中生成一个 URL

【问题讨论】:

    标签: ios objective-c twitter


    【解决方案1】:

    TwitterKit 似乎不公开支持图片。我遇到了同样愚蠢的问题。当使用内置的 tableview 和 datasource 时,API 在内部保存图像。它需要一个 listID 和一个 Slug。但是,当你想要通过 JSON 获取图像时,你就不走运了!甚至TWTRTweet 对象也没有实体或媒体属性!

    不知道怎么会有人开发出如此糟糕的 API。无论如何,我反转了内部进行的服务器调用,发现它发送了其他“未记录”的参数。

    例子:

    TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
    
    NSString *endpoint = @"https://api.twitter.com/1.1/statuses/user_timeline.json";
    
    NSDictionary *params = @{@"screen_name":@"SCREEN_NAME_HERE",
                                 @"count": @"30"};
    

    将返回 NO MEDIA.. 即使您有 @"include_entities" : @"true"

    解决方案:

    TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
    
    NSString *endpoint = @"https://api.twitter.com/1.1/statuses/user_timeline.json";
    
    NSDictionary *params = @{@"screen_name":@"SCREEN_NAME_HERE",
                             @"count": @"30",
                             @"tweet_mode": @"extended"};
    

    tweet_mode 设置为extendedtweet_mode 是一个未记录的参数),它现在将返回媒体作为响应的一部分。这包括图像的“类型”,即“照片”。

    【讨论】:

      【解决方案2】:

      我们可以通过应用带有“include_entities=true”的“filter=images”查询来获取带有图像的推文。它将提供带有媒体实体的推文,在这些推文下我们可以看到 type="photo" 和其他相关数据。

      例如: https://api.twitter.com/1.1/search/tweets.json?q=nature&include_entities=true&filter=images

      在 twitter 开发者控制台尝试这个查询并查看响应格式:https://dev.twitter.com/rest/tools/console

      希望这会有所帮助。

      【讨论】:

      • 您的示例链接无效?但我正在查看开发链接。我差点就放弃了,只是让它保持现状,谢谢,我会研究一下,看看如何实现它
      • @DanielMorrison:示例链接只有在您正确进行身份验证时才有效。此示例仅来自开发链接。您可以在开发链接上按照以下方式尝试:首先您通过“OAuth 1”授权,然后选择搜索 API 方法(/search/tweets.json)。在“查询选项卡”下,在“q”字段中输入“nature”或任何关键字,然后在“include_entities”字段下,输入“true”值。在“自定义/名称”下,将名称作为“过滤器”并将值作为“图像”现在单击“发送”按钮。您将获得上述示例 URL 以及所需的结果。希望它会给你更多的想法.. :)
      猜你喜欢
      • 2012-09-09
      • 1970-01-01
      • 2011-08-26
      • 2011-07-10
      • 2018-02-02
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      相关资源
      最近更新 更多