Как я могу установить эскиз изображения из URL-адреса видео, который поступает с сервера

Я хочу показать миниатюру изображения на URL-адресе видео. Я должен сделать это, но не работает. Это работает только для локального пути к файлу, а не для исходящего с URL-адреса сервера.

URL видео: http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4

-(UIImage *)loadThumbNail:(NSURL *)urlVideo
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:urlVideo options:nil];
    AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    generate.appliesPreferredTrackTransform=TRUE;
    NSError *err = NULL;
    CMTime time = CMTimeMake(1, 60);
    CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
    NSLog(@"err==%@, imageRef==%@", err, imgRef);
    return [[UIImage alloc] initWithCGImage:imgRef];
}

person Kamlesh Shingarakhiya    schedule 08.06.2016    source источник
comment
Обратитесь к этому ответу: stackoverflow.com/questions/37297026/   -  person Jigar Tarsariya    schedule 08.06.2016
comment
Вы можете сделать одну вещь: при загрузке видео вы можете загрузить миниатюру для того же видео с тем же именем с префиксом th_, и при показе видео в режиме просмотра вы можете показать это миниатюрное изображение, и если пользователь хочет просмотреть или загрузить видео в это время, вы можете транслировать или скачать его.   -  person Ajay Gabani    schedule 08.06.2016
comment
@Камлеш Шингаракхия, как ты это решил?   -  person Arpit B Parekh    schedule 17.03.2017
comment
Я решил это, используя ссылку ниже stackoverflow.com/questions/37343358/ первый ответ.   -  person Arpit B Parekh    schedule 17.03.2017
comment
Да, это займет некоторое время, поэтому я назвал код с некоторым интервалом времени, чтобы мой пользовательский интерфейс не зависал.   -  person Arpit B Parekh    schedule 17.03.2017


Ответы (2)


Используйте этот код,

-(UIImage *)loadThumbNail:(NSURL *)urlVideo
{
    AVAsset *avAsset = [AVURLAsset URLAssetWithURL:urlVideo options:nil];

            if ([[avAsset tracksWithMediaType:AVMediaTypeVideo] count] > 0)
            {
                AVAssetImageGenerator *imageGenerator =[AVAssetImageGenerator assetImageGeneratorWithAsset:avAsset];
                Float64 durationSeconds = CMTimeGetSeconds([avAsset duration]);
                CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
                NSError *error;
                CMTime actualTime;


                CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:kCMTimeZero actualTime:&actualTime error:&error];


                if (halfWayImage != NULL)
                {

                    NSString *actualTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));
                    NSString *requestedTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, midpoint));
                    NSLog(@"Got halfWayImage: Asked for %@, got %@", requestedTimeString, actualTimeString);

                    UIImage *img=[UIImage imageWithCGImage:halfWayImage];


                    return img; //self.myimageView.image= img; 

                }

             }

 }

не забудь фреймворк, #import <AssetsLibrary/AssetsLibrary.h>, он у меня работает,

надеюсь, что это полезно.

person Iyyappan Ravi    schedule 08.06.2016

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  {
    return 1;
  }

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return arrVideos.count;
}

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

VideoListingCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

//fetch current object
NSMutableDictionary *dict = [[arrVideos objectAtIndex:indexPath.row] mutableCopy];

//set values
if ([[dict valueForKey:kCaption] isEqual:[NSNull null]])
{
    cell.lblCaption.text =@"No caption";
}
else
{
        cell.lblCaption.text = [dict valueForKey:kCaption];
}


[cell.acivityView startAnimating];
BOOL isNonEmpty = [CommonMethods isNonEmptyString:[dict valueForKey:kThumbnailURL]];

if (isNonEmpty)
{
    NSString *strUrl = [dict valueForKey:kThumbnailURL];
    [cell.imgThumbnail sd_setImageWithURL:[NSURL URLWithString:strUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [cell.acivityView stopAnimating];
    }];
}
else
{
    [cell.imgThumbnail setImage:[UIImage imageNamed:@"img1"]];
    [cell.acivityView stopAnimating];
}
 [cell.imgThumbnail setClipsToBounds:YES];

  return cell;
 }

   - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 //fetch selected object
 NSMutableDictionary *dict = [[arrVideos objectAtIndex:indexPath.row]    mutableCopy];

  ExportVideoVC *obj = [self.storyboard instantiateViewControllerWithIdentifier:@"ExportVideoVC"];
obj.dictPost = [dict mutableCopy];
[self presentViewController:obj animated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
 return 124;
 }

     #pragma mark - webservice calls

   -(void)fetchAllVideos
  {
    //show progress hud
     [SVProgressHUD showWithStatus:kPleaseWait maskType:2];

    //prepare url
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"       video url ", kURL, kMediaType]];

   //ws call
     [[ServerCalls sharedObject] executeRequest:url withData:nil  method:kGET completionBlock:^(NSData *data, NSError *error) {
      if (error)
      {
          ShowAlertWithTitle(@"Please try again later", nil, kOK);

         //reload tableview
         [tblVideos reloadData];
      }
    else if (data)
     {
         NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
         BOOL isSuccess = ![[responseData allKeys] containsObject:kMessage];
        if (isSuccess)
        {
            arrVideos = [[responseData valueForKey:kQuickSpots] mutableCopy];
        }
        else
        {
            ShowAlertWithTitle(@"Please try again later", nil, kOK);
        }
    }

    //reload tableview
    [tblVideos reloadData];

    [SVProgressHUD dismiss];
  }];
  }

это может вам помочь

person Chetan Hedamba    schedule 08.06.2016