XCDYouTubeKit
XCDYouTubeKit copied to clipboard
initWithYoutubeUrl
It would be nice to have an init method that could figure out video identifier from a full youtube url. For a project I am working on, I wrote a category just for that, but maybe others find it useful too and it should be included in XCDYouTubeVideoPlayerViewController source.
Here is my version:
@implementation XCDYouTubeVideoPlayerViewController (Extensions)
- (instancetype)initWithYoutubeUrl:(NSString *)youtubeUrl
{
NSError *error = NULL;
NSString *regexString = @"(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:youtubeUrl options:0 range:NSMakeRange(0, [youtubeUrl length])];
if (match) {
NSRange videoIDRange = [match rangeAtIndex:0];
NSString *y_video_id = [youtubeUrl substringWithRange:videoIDRange];
return [self initWithVideoIdentifier:y_video_id];
}
return NULL;
}
@end
Thanks for your suggestion. I will consider adding this feature in a future version of XCDYouTubeKit.
Thanks for this. I needed this too.
Ditto on this.
+1 It could look something like this:
func extractYoutubeID(_ youtubeURL: String) -> String? {
let pattern: String = "(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)"
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
if let regexMatch = regex.firstMatch(in: youtubeURL, options: [], range: NSMakeRange(0, youtubeURL.characters.count)) {
return (youtubeURL as NSString).substring(with: regexMatch.range)
}
return nil
}
+1 Another solution https://stackoverflow.com/a/27796287/409440