Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the video ID of a YouTube string

(XCode 6.3.2, Swift 1.2)
After researching the internet for the whole evening I already know that this can't be done that easily.
I simply want to get the video ID of a YouTube link. So the "ABCDE" in "https://www.youtube.com/watch?v=ABCDE"

What I got so far:

var url = "https://www.youtube.com/watch?v=ABCDE"
let characterToFind: Character = "="
let characterIndex = find(url, characterToFind)
println(characterIndex)
url.substringFromIndex(advance(url.startIndex, characterIndex))

Prinln outputs: Optional(31)
That's right but I can't use this because it's no index.

XCode also states for the last line: Missing argument for parameter #3 in call
I also don't know what the 3rd parameter of substringFromIndex should be.

Many thanks in advance!

like image 281
Pingu Avatar asked Dec 14 '22 14:12

Pingu


1 Answers

In your case there is no need to create an NSURL as other answers do. Just use:

var url = "https://www.youtube.com/watch?v=ABCDE"
if let videoID = url.componentsSeparatedByString("=").last {
    print(videoID)
}
like image 123
Fidel López Avatar answered Jan 16 '23 02:01

Fidel López