Youtube Video ID From URL - Objective C

后端 未结 16 904
失恋的感觉
失恋的感觉 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:54

    There is a lot of good answers here but I thought it might be beneficial to some to parse multiple video_ID from a string. This could be a web page or an array of different URL.

    Example of page content

    NSString *content = @"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo,http://youtu.be/NLqAF9hrVbY,http://www.youtube.com/watch?v=NLqAF9hrVbY,http://facebook.com,http://www.youtube.com/watch?v=cAcqdjLCN7s";
    

    Method

    -(NSArray *)extractVideos:(NSString *)content {
        NSString *extractRegex = @"(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)"
        NSMutableArray *extractedContent = [[NSMutableArray alloc] init];
        if ([content hasPrefix:@"http://"] || [content hasPrefix:@"https://"]) {
            NSURL *extractURL = [NSURL URLWithString:content];
            if ([extractURL.host rangeOfString:@"youtu"].location != NSNotFound) {
                NSRegularExpression *extractRegex = [NSRegularExpression regularExpressionWithPattern:extractRegex options:NSRegularExpressionCaseInsensitive error:nil];
                NSArray *extractResults = [extractRegex matchesInString:content options:0 range:NSMakeRange(0, content.length)];
                for (NSTextCheckingResult *match in extractResults) {
                    [extractedContent addObject:[content substringWithRange:match.range]];
    
                }
    
            }
    
        }
    
        return extractedContent;
    
    }
    

    Output

    ( 
        NLqAF9hrVbY,
        QLqAF9eeVbY,
        cAcqdjLCN7s
    )
    

    Credit to @Alex for the Regex

提交回复
热议问题