The Man The Man - 6 months ago 308
iOS Question

Youtube Video ID From URL - Objective C

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 web-based programming languages, but none in objective c...

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

Anyone know how to do that or any tutorials out there?

Answer

So a YouTube URL looks something like:

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

The video ID you're interested in is 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, rangeOfFirstMatchInString:options:range: is just about all you need, as seen in Dima's answer.) You can get at the contents of capture groups (as NSTextCheckingResult objects) using firstMatchInString:options:range: or similar methods:

NSError *error = NULL;
NSRegularExpression *regex = 
[NSRegularExpression regularExpressionWithPattern:@"?.*v=([^&]+)"
                                          options:NSRegularExpressionCaseInsensitive
                                            error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:youtubeURL
                                                options:0
                                                  range:NSMakeRange(0, [youtubeURL length])];
if (match) {
    NSRange videoIDRange = [match rangeAtIndex:1];
    NSString *substringForFirstMatch = [youtubeURL substringWithRange:videoIDRange];
}