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
Here is my solution which referenced from StackOveFlow. (Youtube I.D parsing for new URL formats)
I did some modification.
///This is the .h
#import
@interface YoutubeParser : NSObject
+(BOOL) isValidateYoutubeURL:(NSString * )youtubeURL;
+(NSArray *) parseHTML:(NSString *)html ;
@end
///This is the .m
#import "YoutubeParser.h"
@interface YoutubeParser () {
}
@end
@implementation YoutubeParser
#define YOUTUBE_PATTERN @"(https?://)?(www\\.)?(youtu\\.be/|youtube\\.com)?(/|/embed/|/v/|/watch\\?v=|/watch\\?.+&v=)([\\w_-]{11})(&.+)?"
+(NSRegularExpression *)regex {
static NSRegularExpression * regex = nil;
regex = [NSRegularExpression regularExpressionWithPattern:YOUTUBE_PATTERN
options:NSRegularExpressionCaseInsensitive
error:nil];
return regex;
}
+(BOOL) isValidateYoutubeURL:(NSString * )youtubeURL {
NSInteger cnt = [[YoutubeParser regex] numberOfMatchesInString:youtubeURL options:0 range:NSMakeRange(0, [youtubeURL length]) ];
return cnt > 0 ? YES : NO;
}
typedef void (^matching_block_t) (NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop);
+(NSArray *) parseHTML:(NSString *)html {
NSMutableArray * youtubeURLArray = [[NSMutableArray alloc] init];
matching_block_t parseTask = ^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange matchRange = [result range];
NSRange youtubeKey = [result rangeAtIndex:5]; //the youtube key
NSString * strKey = [html substringWithRange:youtubeKey] ;
NSLog(@"youtubeKey=%@ , with url=%@ " ,strKey , [html substringWithRange:matchRange]);
[youtubeURLArray addObject:strKey];
};
[[YoutubeParser regex] enumerateMatchesInString:html options:0 range:NSMakeRange(0, [html length]) usingBlock:parseTask ];
return youtubeURLArray;
}
@end