Youtube Video ID From URL - Objective C

后端 未结 16 896
失恋的感觉
失恋的感觉 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-23 00:01

    Swift 2 version for @Alex answer

    func getYoutubeVideoId(youtubeLink:String) -> String?{
        var youtubeId:String? = nil
        let pattern: String = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
            if let regexMatch = regex.firstMatchInString(youtubeLink, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: youtubeLink.characters.count)) {
                youtubeId = (youtubeLink as NSString).substringWithRange(regexMatch.range)
            }
        }
        catch let error as NSError{
            print("Error while extracting youtube id \(error.debugDescription)")
        }
    
        return youtubeId
    }
    

提交回复
热议问题