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.
//
// 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment