Search code examples
iosswiftxcodeinstagraminstagram-api

How to play instagram video using AVPlayer


I am trying to play an instagram video from shared link , I have used following code but it doesn't stream , is there any additional step required ? Any API which will get the source video URL like graph API on Facebook ?

The URL is like this https://instagram.com/p/BOzamYMA-vb/

let videoURL = NSURL(string: "https://instagram.com/p/BOzamYMA-vb/")
    let player = AVPlayer(url: videoURL! as URL)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
    }

This opens player but doesn't play video Any help is appreciated.


Solution

  • You are giving a web page URL to AVPlayer, this can't work, you have to use the URL for the video itself.

    Using the Fuzi HTML parsing library you can get the video URL from the web page.

    The trick is to find the URL in the HTML.

    For instagram, we can find it with this xpath: "//meta[@property='og:video']/@content".

    Example:

    import Fuzi
    
    let link = "https://instagram.com/p/BOzamYMA-vb/"
    if let pageURL = URL(string: link),
        let data = try? Data(contentsOf: pageURL),
        let doc = try? HTMLDocument(data: data)
    {
        let items = doc.xpath("//meta[@property='og:video']/@content")
        if let item = items.first,
            let url = URL(string: item.stringValue)
        {
            print(url)
        }
    }
    

    This gets the URL from the page, "http://scontent-cdg2-1.cdninstagram.com/t50.2886-16/15872432_382094838793088_926533688240373760_n.mp4", and you can use it to download or stream the video like you would usually do.