Youtube Video Id from URL - Swift3

后端 未结 8 2290
眼角桃花
眼角桃花 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:33

    Here is code to extract youtube video id from any youtube url: (Swift)

    func extractYoutubeId(fromLink link: String) -> String {
            let regexString: String = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
            let regExp = try? NSRegularExpression(pattern: regexString, options: .caseInsensitive)
            let array: [Any] = (regExp?.matches(in: link, options: [], range: NSRange(location: 0, length: (link.characters.count ))))!
            if array.count > 0 {
                let result: NSTextCheckingResult? = array.first as? NSTextCheckingResult
                return (link as NSString).substring(with: (result?.range)!)
            }
    
            return ""
        }
    

提交回复
热议问题