Youtube Video Id from URL - Swift3

后端 未结 8 2496
眼角桃花
眼角桃花 2021-02-15 12:52

Basically I have a Youtube URL as string, I want to extract the video Id from that URL. I found some code in objective c that is as below:

NSError *error = NULL;         


        
8条回答
  •  没有蜡笔的小新
    2021-02-15 13:23

    I have a different way of doing this using URLComponents. You then just select the 'v' parameter from the url, if it exists.

    func getYoutubeId(youtubeUrl: String) -> String? {
        return URLComponents(string: youtubeUrl)?.queryItems?.first(where: { $0.name == "v" })?.value
    }
    

    And then pass in a Youtube url like this:

    print (getYoutubeId(youtubeUrl: "https://www.youtube.com/watch?v=Y7ojcTR78qE&spfreload=9"))
    

提交回复
热议问题