Skip to content

Instantly share code, notes, and snippets.

@hechen
Created August 4, 2020 03:32
Show Gist options
  • Save hechen/d3e4959bcf643ea012d2da4c43e51de7 to your computer and use it in GitHub Desktop.
Save hechen/d3e4959bcf643ea012d2da4c43e51de7 to your computer and use it in GitHub Desktop.

Revisions

  1. hechen created this gist Aug 4, 2020.
    55 changes: 55 additions & 0 deletions YoutubeID Parser
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    //
    // YTBParser.swift
    // SideloadExt
    //
    // Created by chen he on 2020/7/30.
    // Copyright © 2020 chen he. All rights reserved.
    //

    import Foundation

    struct YTBParser {
    static func videoID(fromVideoURL videoURL: URL) -> String? {
    if videoURL.host == "youtu.be" {
    return videoURL.pathComponents.second
    } else if videoURL.absoluteString.contains("www.youtube.com/embed") {
    return videoURL.pathComponents.third
    } else if videoURL.host?.contains("youtube.googleapis.com") == true || videoURL.pathComponents.first == "www.youtube.com" {
    return videoURL.pathComponents.third
    } else {
    return videoURL.extractedParamsFromQuery["v"]?.first
    }
    }
    }

    extension Array {
    var second: Element? {
    return count >= 2 ? self[1] : nil
    }
    var third: Element? {
    return count >= 3 ? self[2] : nil
    }
    }
    extension URL {
    var extractedParamsFromQuery: [AnyHashable: [String]] {
    return query?.dictionaryFromQueryStringComponents() ?? [:]
    }
    }
    extension String {
    func stringBydecodingURLFormat() -> String? {
    return replacingOccurrences(of: "+", with: " ").removingPercentEncoding
    }

    func dictionaryFromQueryStringComponents() -> [String: [String]] {
    var params: [String: [String]] = [:]
    for key in components(separatedBy: "&") {
    let keyValue = key.components(separatedBy: "=")
    if let key = keyValue.first, let value = keyValue.second {
    var values = params[key] ?? []
    values.append(value)
    params[key] = values
    }
    }
    return params
    }
    }