Youtube Video ID From URL - Objective C

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

    Merging some of your answers, I'd say this is the best answer:

    + (NSString *)extractYoutubeID:(NSString *)youtubeURL
    {
        NSError *error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)"
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
        NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:youtubeURL options:NSMatchingReportProgress range:NSMakeRange(0, [youtubeURL length])];
        if(rangeOfFirstMatch.location != NSNotFound) {
            NSString *substringForFirstMatch = [youtubeURL substringWithRange:rangeOfFirstMatch];
    
            return substringForFirstMatch;
        }
    
        return nil;
    }
    

提交回复
热议问题