Youtube Video Id from URL - Swift3

后端 未结 8 2334
眼角桃花
眼角桃花 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条回答
  •  旧时难觅i
    2021-02-15 13:46

    Some samples of Youtube's url:

    let urls: [String] = [
        "www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0",
        "http://www.youtube.com/watch?v=peFZbP64dsU",
        "http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel",
        "http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player",
        "http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player",
        "http://youtu.be/6dwqZw0j_jY",
        "http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_playe",
        "http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player",
        "http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player",
        "http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player",
        "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0",
        "http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY",
        "1p3vcRhsY02"
    ]
    

    My extension based on Islam Q. solution:

    private extension String {
        var youtubeID: String? {
            let pattern = "((?<=(v|V|vi)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=vi=)|(?<=/u/[0-9_]/)|(?<=embed/))([\\w-]++)"
            let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
            let range = NSRange(location: 0, length: count)
    
            guard let result = regex?.firstMatch(in: self, range: range) else {
                return count == 11 ? self : nil
            }
    
            let id = (self as NSString).substring(with: result.range)
            return id.count == 11 ? id : nil
        }
    }
    

提交回复
热议问题