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…
So a YouTube URL looks something like:
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
NSRegularExpressionclass. 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 onv=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=([^&]+). Thev=gets us to the right part of the query URL (in case we get something likewatch?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 thev=whateverfield, and no fields after it if you get a URL likewatch?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 (asNSTextCheckingResultobjects) usingfirstMatchInString:options:range:or similar methods: