2

我正在尝试使用查询来简单地搜索视频,使用以下代码可以完美地工作。

  // Create a service object for executing queries
GTLServiceYouTube *service = [[GTLServiceYouTube alloc] init];
// Services which do not require sign-in may need an API key from the
// API Console
service.APIKey = @"AIzaSyA-e4NldR2o8vYPpL6IcAcMH3HSnEpPPJY";
// Create a query
GTLQueryYouTube *query = [GTLQueryYouTube queryForSearchListWithPart:@"id,snippet"];
query.maxResults = 10;
query.q = searchBar.text;
query.videoEmbeddable = @"true";
query.type = @"video";
//query.country = @"US";
// Execute the query
GTLServiceTicket *ticket = [service executeQuery:query
                               completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {
                                   // This callback block is run when the fetch completes
                                   if (error == nil) {
                                       GTLYouTubeSearchListResponse *products = object;

                                       [videoArray removeAllObjects];
                                       // iteration of items and subscript access to items.
                                       for (GTLYouTubeSearchResult *item in products) {



                                           NSMutableDictionary *dictionary = [item JSONValueForKey:@"id"];

                                           NSLog(@"%@", [dictionary objectForKey:@"videoId"]);
                                           YoutubeVideo *video = [[YoutubeVideo alloc]init];
                                           [video setLblTitle:item.snippet.title];

                                           //Get youtube video image
                                           [video setImgIconURL:[NSURL URLWithString:item.snippet.thumbnails.defaultProperty.url]];


                                           [video setLblVideoURL:[dictionary objectForKey:@"videoId"]];

                                           [video setLblChannelTitle:item.snippet.channelTitle];
                                           [videoArray addObject:video];


                                       }
                                       reloadData = YES;
                                       [tableView reloadData];

                                       //Download images asynchronously
                                       [NSThread detachNewThreadSelector:@selector(downloadImages)
                                                                toTarget:self
                                                              withObject:nil];
                                   }else{
                                       NSLog(@"Error: %@", error.description);
                                   }
                               }];

但是,现在我想显示有关视频的某些信息。我可以从中得到一些信息

  item.snippet

但我还需要获取视频持续时间和观看次数。如何使用 Youtube API 3.0 获取它们?我也有一个想法尝试为此使用 GData,但它实际上使加载时间增加了三倍

  NSString *JSONString = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://gdata.youtube.com/feeds/api/videos/%@?v=2&alt=json", [video lblVideoURL]]] encoding:NSUTF8StringEncoding error:nil ];

如何获取视频的时长以及视频的观看次数?

4

3 回答 3

0

从搜索 API 收集 id 并执行另一个视频列表 API 调用是完成您想要实现的目标的正确方法。视频列表 API 调用可以将多个视频 id 以逗号分隔在同一个调用中。额外的调用不应考虑耗尽,因为这是API v3 上的预期行为:

项目成员 #1 je...@google.com

这是预期的行为,不太可能改变。由于 search.list() 方法可以返回频道、视频和播放列表,因此只有对所有这些资源类型有意义的属性才会在搜索响应中返回。如果您需要获取任何其他属性,则需要对 videos.list() 等进行后续请求。请注意,您最多可以将 50 个视频 ID 传递给 videos.list(),因此您可以在单个 video.list() 调用中有效地查找整个页面的 search.list() 结果。

如果您尝试https://developers.google.com/youtube/v3/docs/videos/list#try-it,您将contentDetails,statistics设置为部分,您应该能够得到以下结果:

"contentDetails": { "duration": "PT20M38S", "dimension": "2d", "definition": "hd", "caption": "false", "licensedContent": false },

“统计”:{“viewCount”:“191”,“likeCount”:“7”,“dislikeCount”:“0”,“favoriteCount”:“0”,“commentCount”:“0”}

PT20M38S表示 20 分 38 秒,基于 ISO 8601 ( http://en.wikipedia.org/wiki/ISO_8601 )

于 2013-04-05T07:57:28.327 回答
0

搜索查询仅接受 ID 和 Snippet 作为部分。如果您更改为视频列表查询,您可以包含其他部分,但您必须使用其中一个过滤器。

我认为您必须通过搜索查询获取视频 ID,然后按 ID(您获得的 ID)过滤另一个查询(现在是视频查询),而不是获得您搜索的视频的所有其他信息。

问题是我在获取视频 ID 时遇到问题,我认为 API 使用“标识符”一词而不是“id”,因为它是 Objective-c 的保留词。

编辑:是的,这只是时间问题,只需请求我的 GTLYoutubeSearchResponse.JSON,然后按照我的意愿进行操作。

第一个查询:

GTLQueryYouTube *query = [GTLQueryYouTube queryForSearchListWithPart:@"id,snippet"];
query.maxResults = 10;
query.q = @"iphone";
query.fields = @"items(id,snippet)";
query.order = @"viewCount";
//query.channelId = @"UCsnbNwitAF9BzjjdMfRyK2g";//Kavaco

[appDelegate.service executeQuery:query
    completionHandler:^(GTLServiceTicket *ticket,
                        id object,
                        NSError *error) {
        if (error == nil) {
            appDelegate.videos = object;

            [self performSegueWithIdentifier:@"videoList" sender:self];

        }
        else {
            NSLog(@"%@", error.description);
        }
    }];

第二个查询:在我的 TableViewController 中,在我的 cellForRowAtIndexPath 中,我对找到的每个视频进行另一个查询。确保只请求您需要的变量以避免花费您的积分,在我的情况下,我只请求 viewCount。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];

GTLYouTubeVideo *video = appDelegate.videos[indexPath.row];

NSMutableDictionary *videoIdJson = [video.JSON objectForKey:@"id"];
NSString *videoId = [videoIdJson objectForKey:@"videoId"];

cell.textLabel.text = video.snippet.title;


GTLQueryYouTube *query = [GTLQueryYouTube queryForVideosListWithPart:@"statistics"];
query.identifier = videoId;
query.maxResults = 1;
query.fields = @"items/statistics(viewCount)";

[appDelegate.service executeQuery:query
                completionHandler:^(GTLServiceTicket *ticket,
                                    id object,
                                    NSError *error) {
                    if (error == nil) {
                        GTLYouTubeVideoListResponse *detalhe = object;

                        NSMutableDictionary *responseJSON = detalhe.JSON;
                        NSArray *tempArray = [responseJSON objectForKey:@"items"];
                        NSMutableDictionary *items = tempArray[0];
                        NSMutableDictionary *statistics = [items objectForKey:@"statistics"];

                        _views = [[NSString alloc] initWithFormat:@"Views: %@",[statistics objectForKey:@"viewCount"]];
                        cell.detailTextLabel.text = _views;

                    }
                    else {
                        NSLog(@"%@", error.description);
                    }
                }];

cell.detailTextLabel.text = _views;


return cell;
}

希望能帮助到你。

于 2014-11-28T15:27:54.477 回答
0

最好的方法是:

if (!service) {
        service = [[GTLServiceYouTube alloc] init];
        service.shouldFetchNextPages = YES;
        service.shouldFetchInBackground = YES;
        service.retryEnabled = YES;
        service.APIKey = @"AIzaSyDSO2JPnM_r9VcDrDJJs_d_7Li2Ttk2AuU";
    }
    [youtubeList removeAllObjects];

    GTLQueryYouTube *query = [GTLQueryYouTube queryForSearchListWithPart:@"id"];
    query.maxResults = 50;
    query.q = withText;
    query.fields = @"items(id)";
    query.order = @"viewCount";
    query.type = @"video";
//    query.videoDuration = @"long";//any-long-medium-short

    __block NSInteger incrementRequest = 0;
    [service executeQuery:query completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {
        if (error) {
            NSLog(@"Error is!! = %@", error.localizedDescription);
            return;
        }
        GTLYouTubeVideoListResponse *idsResponse = object;
        for (GTLYouTubeVideoListResponse *videoInfo in object) {
            [youtubeList addObject:videoInfo.JSON];

            GTLQueryYouTube *query2 = [GTLQueryYouTube queryForVideosListWithIdentifier:[[videoInfo.JSON valueForKey:@"id"] valueForKey:@"videoId"] part:@"id,contentDetails,snippet,statistics"];
            query2.maxResults = 1;
            query2.fields = @"items(id,contentDetails,snippet,statistics)";
            query2.order = @"viewCount";

            [service executeQuery:query2 completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {
                if (error) {
                    NSLog(@"Error is!! = %@", error.localizedDescription);
                    return;
                }
                GTLYouTubeVideoListResponse *detalhe = object;

                for (NSMutableDictionary *tmpDict in youtubeList) {
                    if ([[[tmpDict valueForKey:@"id"] valueForKey:@"videoId"] isEqualToString:[[[detalhe.JSON valueForKey:@"items"] objectAtIndex:0] valueForKey:@"id"]]) {
                        [tmpDict removeObjectForKey:@"id"];
                        //condition personal
                        if (![Utils parseISO8601TimeIsGrater30:[[[[detalhe.JSON valueForKey:@"items"] objectAtIndex:0] valueForKey:@"contentDetails"] valueForKey:@"duration"]]) {
                            BOOL isBlockedInUs = NO;
                            for (NSString *countryRestric in [[[[[detalhe.JSON valueForKey:@"items"] objectAtIndex:0] valueForKey:@"contentDetails"] valueForKey:@"regionRestriction"] valueForKey:@"blocked"]) {
                                if ([countryRestric isEqualToString:@"US"]) {
                                    isBlockedInUs = YES;
                                    break;
                                }
                            }
                            if (!isBlockedInUs) {
                                [tmpDict addEntriesFromDictionary:detalhe.JSON];
                                [tmpDict setValue:[[[[detalhe.JSON valueForKey:@"items"] objectAtIndex:0] valueForKey:@"snippet"] valueForKey:@"publishedAt"] forKey:@"publishedAt"];
                            } else {
                                [youtubeList removeObject:tmpDict];
                            }
                        } else {
                            [youtubeList removeObject:tmpDict];
                        }

                        break;
                    }
                }

                incrementRequest ++;
                if ([idsResponse.items count] == incrementRequest) {
                    //Finish
                    [self.tableView reloadData];
                }
            }];
        }
    }];
于 2015-10-27T22:11:22.240 回答