Youtube Video ID From URL - Objective C

后端 未结 16 886
失恋的感觉
失恋的感觉 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-23 00:01

    - (NSString*)getYoutubeVideoID:(NSString*)url {
        NSError *error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*"
                                                  options:NSRegularExpressionCaseInsensitive
                                                    error:&error];
    
        NSTextCheckingResult *match = [regex firstMatchInString:url
                                                        options:0
                                                          range:NSMakeRange(0, [url length])];
        NSString *substringForFirstMatch;
        if (match) {
            NSRange videoIDRange = [match rangeAtIndex:0];
            substringForFirstMatch = [url substringWithRange:videoIDRange];
        }
        return substringForFirstMatch;
    }
    

提交回复
热议问题