YouTube Video ID From URL - Swift or Objective-C

Viewed 16884

I have a Youtube url as an NSString or Swift String, 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 web-based programming languages, but none in Objective-C or Swift for Apple platforms...

I'm looking for a method that asks for an NSString url as the parameter and returns the video id as another NSString...

17 Answers

Swift 5

Here is the latest working version I am using. I've added support for YouTube short videos as well. Ex: https://youtube.com/shorts/2xL2WlQM7Nc

extension String{
  func extractYoutubeId() -> String? {
    let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/)|(?<=shorts/))([\\w-]++)"
    if let matchRange = self.range(of: pattern, options: .regularExpression) {
        return String(self[matchRange])
    } else {
        return .none
    }
  }
}

Example:

let ytShortVideoLink = "https://youtube.com/shorts/2xL2WlQM7Nc"
print("Video ID:",ytShortVideoLink. extractYoutubeId())
//Output: 
Video ID: 2xL2WlQM7Nc
Related