Youtube Video Id from URL - Swift3

后端 未结 8 2292
眼角桃花
眼角桃花 2021-02-15 12:52

Basically I have a Youtube URL as string, I want to extract the video Id from that URL. I found some code in objective c that is as below:

NSError *error = NULL;         


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-15 13:22

    Swift 5

    var youtubeURLs = [
        "http://www.youtube.com/watch?v=-wtIMTCHWuI",
        "http://www.youtube.com/v/-wtIMTCHWuI?version=3&autohide=1",
        "http://youtu.be/-wtIMTCHWuI",
        "http://www.youtube.com/oembed?url=http%3A//www.youtube.com/watch?v%3D-wtIMTCHWuI&format=json",
        "https://youtu.be/uJ2PZaO1N5E",
        "https://www.youtube.com/embed/M7lc1UVf-VE",
        "http://www.youtube.com/attribution_link?a=JdfC0C9V6ZI&u=%2Fwatch%3Fv%3DEhxJLojIE_o%26feature%3Dshare",
        "https://www.youtube.com/attribution_link?a=8g8kPrPIi-ecwIsS&u=/watch%3Fv%3DyZv2daTWRZU%26feature%3Dem-uploademail"
    ]
    
    func getVideoID(from urlString: String) -> String? {
        guard let url = urlString.removingPercentEncoding else { return nil }
        do {
            let regex = try NSRegularExpression.init(pattern: "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)", options: .caseInsensitive)
            let range = NSRange(location: 0, length: url.count)
            if let matchRange = regex.firstMatch(in: url, options: .reportCompletion, range: range)?.range {
                let matchLength = (matchRange.lowerBound + matchRange.length) - 1
                if range.contains(matchRange.lowerBound) &&
                    range.contains(matchLength) {
                    let start = url.index(url.startIndex, offsetBy: matchRange.lowerBound)
                    let end = url.index(url.startIndex, offsetBy: matchLength)
                    return String(url[start...end])
                }
            }
        } catch {
            print(error.localizedDescription)
        }
        return nil
    }
    
    for url in youtubeURLs {
        print("Video id: \(getVideoID(from: url) ?? "NA") for url: \(url)")
    }
    

    Result:

    Video id: -wtIMTCHWuI for url: http://www.youtube.com/watch?v=-wtIMTCHWuI
    Video id: -wtIMTCHWuI for url: http://www.youtube.com/v/-wtIMTCHWuI?version=3&autohide=1
    Video id: -wtIMTCHWuI for url: http://youtu.be/-wtIMTCHWuI
    Video id: -wtIMTCHWuI for url: http://www.youtube.com/oembed?url=http%3A//www.youtube.com/watch?v%3D-wtIMTCHWuI&format=json
    Video id: uJ2PZaO1N5E for url: https://youtu.be/uJ2PZaO1N5E
    Video id: M7lc1UVf-VE for url: https://www.youtube.com/embed/M7lc1UVf-VE
    Video id: EhxJLojIE_o for url: http://www.youtube.com/attribution_link?a=JdfC0C9V6ZI&u=%2Fwatch%3Fv%3DEhxJLojIE_o%26feature%3Dshare
    Video id: yZv2daTWRZU for url: https://www.youtube.com/attribution_link?a=8g8kPrPIi-ecwIsS&u=/watch%3Fv%3DyZv2daTWRZU%26feature%3Dem-uploademail
    

提交回复
热议问题