Youtube Video ID From URL - Objective C

后端 未结 16 908
失恋的感觉
失恋的感觉 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条回答
  •  旧时难觅i
    2020-12-22 23:55

    You don't even need regexes. The following works regardless of the length of the video ID and its position within the URL:

    NSString *vID = nil;
    NSString *url = @"http://www.youtube.com/watch?v=cAcqdjLCN7s";
    
    NSString *query = [url componentsSeparatedByString:@"?"][1];
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        if ([kv[0] isEqualToString:@"v"]) {
            vID = kv[1];
            break;
        }
    }
    
    NSLog(@"%@", vID);
    

提交回复
热议问题