Youtube Video ID From URL - Objective C

后端 未结 16 916
失恋的感觉
失恋的感觉 2020-12-22 23:23

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

16条回答
  •  暖寄归人
    2020-12-22 23:50

    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
    

提交回复
热议问题