Created
August 4, 2020 03:32
-
-
Save hechen/d3e4959bcf643ea012d2da4c43e51de7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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