Skip to content

Instantly share code, notes, and snippets.

@kylehowells
Created September 5, 2014 20:08
Show Gist options
  • Save kylehowells/97b256056dd0ef53e18d to your computer and use it in GitHub Desktop.
Save kylehowells/97b256056dd0ef53e18d to your computer and use it in GitHub Desktop.
A method to try and retrieve the Youtube video ID from a string. (designed to parse user input, hence the multiple accepted formats).
/// Accepts any of the following formats
//
// - The Youtube ID itself:
// 1. yj4OtpHl8EE
//
// - A youtu.be short URL:
// 2. http://youtu.be/yj4OtpHl8EE
//
// - A normal youtube.com URL:
// 3. http://www.youtube.com/watch?v=ZvmMzI0X7fE
//
// - A complex youtube.com URL
// 4. https://www.youtube.com/watch?v=mHeo62B0d0E&index=13&list=FLJ6Kj3NntkXiV-u2TTBO9w
//
-(NSString*)youtubeIDForString:(NSString*)inputString{
NSString *videoIDString = inputString;
BOOL httpFound = [videoIDString rangeOfString:@"http"].location != NSNotFound;
BOOL wwwFound = [videoIDString rangeOfString:@"www"].location != NSNotFound;
BOOL comFound = [videoIDString rangeOfString:@"com"].location != NSNotFound;
BOOL slashFound = [videoIDString rangeOfString:@"/"].location != NSNotFound;
if (slashFound || comFound || wwwFound || httpFound) {
// It is likely a URL
BOOL vFound = [videoIDString rangeOfString:@"v="].location != NSNotFound;
if (vFound) {
// We found the v=, now parse the URL
NSRange vRange = [videoIDString rangeOfString:@"v="];
NSMutableString *string = videoIDString.mutableCopy;
[string replaceCharactersInRange:NSMakeRange(0, vRange.location) withString:@""];
NSMutableDictionary *keyValues = [NSMutableDictionary dictionary];
NSArray *stringParts = [string componentsSeparatedByString:@"&"];
if (stringParts.count > 0) {
for (NSString *subString in stringParts) {
NSArray *keyValue = [subString componentsSeparatedByString:@"="];
if (keyValue.count == 2) {
[keyValues setValue:[keyValue objectAtIndex:1] forKey:[keyValue objectAtIndex:0]];
}
}
}
return keyValues[@"v"];
}
else {
NSArray *stringParts = [videoIDString componentsSeparatedByString:@"/"];
return stringParts.lastObject;
}
}
else if (videoIDString.length > 0) {
return videoIDString;
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment