我无法在文档目录中保存或下载视频,无法在文档目录中播放

时间:2016-04-07 04:32:50

标签: ios video download youtube mpmovieplayercontroller

我想在文档目录中下载保存 YouTube视频,然后使用播放该视频> MPMoviePlayerViewController 即可。但我不知道为什么我的代码无效。

我使用以下代码:

prgrma mark-下载或保存

-(IBAction)onclick_download:(id)sender
{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Downloading Started");
        NSString *urlToDownload = @"youtubeurl";
        NSURL  *url = [NSURL URLWithString:urlToDownload];
        NSData *urlData = [NSData dataWithContentsOfURL:url];
        if ( urlData )
        {
            NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString  *documentsDirectory = [paths objectAtIndex:0];

            filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"thefile.mp4"];

            //saving is done on main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                [urlData writeToFile:filePath atomically:YES];
                NSLog(@"File Saved !");
            });
        }

    });

}

pragma mark-播放文档目录中的视频

-(IBAction)onclick_playvideolocally:(id)sender
{
    [self playvideolocally];
}
-(void)playvideolocally
{
    NSURL *videoUrl;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
    NSLog(@"files array %@", filePathsArray);

    NSString *fullpath;

    for ( NSString *apath in filePathsArray )
    {
        fullpath = [documentsDirectory stringByAppendingPathComponent:apath];
        videoUrl =[NSURL fileURLWithPath:fullpath];
    }
    MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:videoUrl];
    [self presentMoviePlayerViewControllerAnimated:videoPlayerView];
    [videoPlayerView.moviePlayer play];
}

1 个答案:

答案 0 :(得分:2)

由于您在网址中提供的链接适用于youtube,因此不会下载或保存在本地

将此用于youtube

我使用过这个项目中的类:https://github.com/larcus94/LBYouTubeView它适用于我。我可以下载youtube视频。

11