Alex Rivera | Logout

YouTube Video ID From URL - Swift or Objective-C

Asked 2012-07-16T17:09:41.417
24

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...

Edit
Report

1 Answer

15

So a YouTube URL looks something like:

http://www.youtube.com/watch?v=oHg5SJYRHA0

The video ID you're interested in is the part at the end (oHg5SJYRHA0).... though it's not necessarily at the end, as YouTube URLs can contain other parameters in the query string.

Your best bet is probably to use a regular expression and Foundation's NSRegularExpression class. I'd presume this approach is used in the other-language tutorials you've found -- note that the content of regular expressions is pretty much the same in any language or toolkit which includes them, so any regex found in those tutorials should work for you. (I'd advise against your approach of breaking on v= and taking exactly 11 characters, as this is prone to various modes of failure to which a regex is more robust.)

To find the video ID you might want a regex like v=([^&]+). The v= gets us to the right part of the query URL (in case we get something like watch?fmt=22&v=oHg5SJYRHA0). The parentheses make a capture group so we can extract only the video ID and not the other matched characters we used to find it, and inside the parentheses we look for a sequence of one or more characters which is not an ampersand -- this makes sure we get everything in the v=whatever field, and no fields after it if you get a URL like watch?v=oHg5SJYRHA0&rel=0.

Whether you use this or another regex, it's likely that you'll be using capture groups. (If not, answered 2012-07-16T18:14:08.157

Your Answer