XCDYouTubeKit icon indicating copy to clipboard operation
XCDYouTubeKit copied to clipboard

initWithYoutubeUrl

Open gintsmurans opened this issue 10 years ago • 5 comments

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

gintsmurans avatar Jun 15 '14 23:06 gintsmurans

Thanks for your suggestion. I will consider adding this feature in a future version of XCDYouTubeKit.

0xced avatar Jun 16 '14 23:06 0xced

Thanks for this. I needed this too.

pbassut avatar Nov 15 '14 06:11 pbassut

Ditto on this.

Shagans982 avatar Mar 09 '15 20:03 Shagans982

+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
    }

A1iAshoor avatar Oct 11 '16 19:10 A1iAshoor

+1 Another solution https://stackoverflow.com/a/27796287/409440

yakubbaev avatar Oct 05 '17 08:10 yakubbaev