How to play youtube/vimeo video within the application in iPhone

前端 未结 9 2168
[愿得一人]
[愿得一人] 2020-12-23 02:42

I am building an application where I want to play video from url like Youtube, Vimeo, Direct url. I am making custom player using AVPlayer to play a video from a direct url

相关标签:
9条回答
  • 2020-12-23 02:58

    I don't know about the Vimeo but for youtube videos you can use HCYouTubeParser to fetch mp4 urls for the youtube videos which can be later played on AVPlayer or MpMoviePlayerVC as per requirements.

    0 讨论(0)
  • 2020-12-23 03:00

    I have used WKWebView in storyboard with constraints and added code :

    func playVideo() {
    
    if yourLink.lowercased().contains("youtu.be"){
        getVideo(videoCode: yourVideoCode)
        if let range = yourLink.range(of: "be/"){
            let videoId = yourLink[range.upperBound...].trimmingCharacters(in: .whitespaces)
            getVideo(videoCode: videoId)
        }
    } else if yourLink.lowercased().contains("youtube.com"){
        if let range = yourLink.range(of: "?v="){
            let videoId = yourLink[range.upperBound...].trimmingCharacters(in: .whitespaces)
            getVideo(videoCode: videoId)
        }
    } else if yourLink.lowercased().contains("vimeo.com") {
        let url: NSURL = NSURL(string: yourLink)
        webKitView.contentMode = UIViewContentMode.scaleAspectFit
        webKitView.load(URLRequest(url: url as URL))
    }
    }
    
    func getVideo(videoCode: String) {
        guard
        let url = URL(string: "https://www.youtube.com/embed/\(videoCode)")
        else { return }
        webKitView.load(URLRequest(url: url))
    }
    

    To get videoId from youtube/Vimeo links, please refer to :

    Youtube Video Id from URL - Swift3

    Regex to get vimeo video id in swift 2

    Hope will help! :)

    0 讨论(0)
  • 2020-12-23 03:03

    I used youtube and vimeo in my Project, I share my codings for you it will very hopeful for you

    in my view controller.m

    //Button action
    
    - (IBAction)importAudioClip:(id)sender
    {
    flag = 0;
    customActionSheet = [[UIActionSheet alloc]initWithTitle:@"Select Audio/Video from:" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"YouTube",@"Vimeo", nil];
    [customActionSheet showInView:self.view];
    
    }
    
    
    #pragma ActionSheet Delegate Methods
    -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
    {
      NSLog(@"CLiekc button is %i",buttonIndex);
    
     if([actionSheet.title isEqualToString:@"Select Audio/Video from:"])
        {
            if (buttonIndex == 0)
            {
                videoStatus=0;
    
                webView.hidden = NO;
    
                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.youtube.com"]]];
                NSLog(@"Taking from Youtube");
    
            }
            else if (buttonIndex == 1)
            {
                videoStatus=1;
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"Vimeo" message:@"Please enter Vimeo Username" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
                alertView.tag=123;
                alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
                [alertView show];
    
            }
        }
    }
    
    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
    if (alertView.tag==123)
        {
        if (buttonIndex==1)
        {
            templateText=[[UITextField alloc]init];
            templateText = [alertView textFieldAtIndex:0];
            templateText.autocapitalizationType=UITextAutocapitalizationTypeWords;
            templateText.delegate=self;
            if ([templateText.text length]!=0)
            {
                NSString *str=[templateText.text capitalizedString];
                NSLog(@"Str== %@",str);
                [self getVimeoDetails:str];
    
            }
        }
    }
    }
    
    
    -(void)getVimeoDetails:(NSString*)userName
    {
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://vimeo.com/api/v2/%@/videos.json",userName]]];
    [request setHTTPMethod:@"GET"];
    NSError *err;
    NSURLResponse *response;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
    NSLog(@"The value is==%@",resSrt);
    vimeoDetailsArray =(NSArray*) [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
    NSLog(@"jsonObject== %i",[vimeoDetailsArray count]);
    NSString *theReply = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding: NSASCIIStringEncoding];
    NSLog(@"the reply == %@",theReply);
    if(response)
    {
        if (vimeoDetailsArray==NULL)
        {
            NSLog(@"its Null");
            NSLog(@"null response== %@",response);
            //                     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert!!!" message:[NSString stringWithFormat:@"%@",theReply] delegate:self
            //                                                        cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            //                     [alert show];
            // [self performSelector:@selector(showAlertMessage:theReply withTitle:@"Alert!!!") withObject:nil afterDelay:5];
            vimeoVideoTable.hidden=YES;
            [self showAlertMessage:[NSString stringWithFormat:@"%@",theReply] withTitle:@"Alert!!!"];
        }
        else
        {
            [self createTableView];
            vimeoVideoTable.hidden=NO;
            [vimeoVideoTable reloadData];
            NSLog(@"got response== %@",response);
        }
    }
    else
    {
        NSLog(@"faield to connect");
    }
    
    
    if ([responseData length] == 0 && err == nil)
    {
        NSLog(@"Nothing was downloaded.");
    }
    else if (err != nil){
    
        if ([[err description] rangeOfString:@"The Internet connection appears to be offline"].location != NSNotFound)
        {
            NSLog(@"string does not contain ");
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert!!!" message:@"Please Check your Internet Connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
        NSLog(@"Error = %@", err);
    }
    
    }
    
    -(void)createTableView
    {
    if (vimeoVideoTable !=nil)
    {
        [vimeoVideoTable removeFromSuperview];
        vimeoVideoTable=nil;
    }
    vimeoVideoTable=[[UITableView alloc]initWithFrame:CGRectMake(10, 20, 300, self.view.bounds.size.height-100)];
    [vimeoVideoTable setDelegate:self];
    [vimeoVideoTable setHidden:YES];
    [vimeoVideoTable setDataSource:self];
    [self.view addSubview:vimeoVideoTable];
    //[vimeoVideoTable reloadData];
    
    }
    
    0 讨论(0)
  • 2020-12-23 03:05

    I used the following method to solve the same problem successfully.

    Use youtube-ios-player-helper and add the code:

    [_playerView loadWithVideoId:@"DmTzboEqfNk" playerVars:@{
                                                             @"playsinline" : @1
                                                             }];
    

    You can find more vars in Youtube > IFrame API.

    0 讨论(0)
  • 2020-12-23 03:07

    I definitely suggest youtube_ios_player_helper, "sponsored by" Google.

    import youtube_ios_player_helper
    
    class YTViewController: YTPlayerViewDelegate {
    
        @IBOutlet weak var player: YTPlayerView!
    
        // MARK: - Public properties -
    
        var videoID = "k_okcNVZqqI"
    
        // MARK: - View life cycle -
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.player.delegate = self
        }
    
        override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
            self.load()
            self.player.fadeOut()
        }
    
        /**
         Play video with the relative youtube identifier.
         */
        func load() {
            Utils.showHUD(self.view)
            let options = ["playsinline" : 1]
            self.player.loadWithVideoId(self.videoID, playerVars: options)
        }
    
        /**
         Stop video playing.
         */
        func stop() {
        }
    
        // MARK: - YOUTUBE video player delegate -
    
        func playerViewDidBecomeReady(playerView: YTPlayerView) {
            self.player.playVideo()
        }
    
        func playerView(playerView: YTPlayerView, didChangeToState state: YTPlayerState) {
            switch state {
            case .Playing:
                self.player.fadeIn(duration: 0.5)
                Utils.hideHUD(self.view)
                print("Started playback")
                break;
            case .Paused:
                print("Paused playback")
                break;
            default:
                break;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-23 03:11

    If you wanna play youtube, here's a link to youtube player project on github, It's really helpful. and yes it is possible to play it in your uiwebview, just give the webview the url and tell it to load, it shouldn't open in the default player, as far as i believe at least.

    0 讨论(0)
提交回复
热议问题