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

前端 未结 9 2242
[愿得一人]
[愿得一人] 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 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! :)

提交回复
热议问题