Youtube Video ID From URL - Objective C

后端 未结 16 897
失恋的感觉
失恋的感觉 2020-12-22 23:23

I basically have a Youtube url as an NSString, but I need to extract the video id that is displayed in the url. I found many tutorials on how to do this in php or and other

16条回答
  •  感情败类
    2020-12-22 23:48

    Here is the swift version using @jt_ik's regex:

    func extractYoutubeID(youtubeURL: String) -> String {
        var error: NSError?
        let pattern: String = "(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)"
        let regex = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)!
    
        if error == nil {
            if let regexMatch = regex.firstMatchInString(youtubeURL, options: nil, range: NSRange(location: 0, length: youtubeURL.utf16Count)) {
                return (youtubeURL as NSString).substringWithRange(regexMatch.range)
            }
            // Handle no match here
            return ""
        } else {
            // Handle error here
            println(error?.userInfo)
            return ""
        }
    }
    

提交回复
热议问题