Last active
February 15, 2019 03:27
-
-
Save sho-ito-1027/edc8750f010e74d429b9886c84138bf6 to your computer and use it in GitHub Desktop.
youtube api for playground (Swift 4)
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
import UIKit | |
let youtubeURLs: [String] = [ | |
"https://www.youtube.com/get_video_info?video_id=e0okrDbEsXM", | |
"https://www.youtube.com/get_video_info?video_id=Dwh9hpBWtYQ", | |
"https://www.youtube.com/get_video_info?video_id=aNyNLEoPx4k"//, | |
// "https://www.youtube.com/get_video_info?video_id=mM5_T-F1Yn4", | |
// "https://www.youtube.com/get_video_info?video_id=XYra2ovcWxE" | |
] | |
let semaphore = DispatchSemaphore(value: 0) | |
func getURL(_ url: String, completion: @escaping (_ url: String) -> Void) { | |
var req = URLRequest(url: URL(string: url)!) | |
req.httpMethod = "GET" | |
let task = URLSession.shared.dataTask(with: req, completionHandler: { data, response, error in | |
print(error ?? "") | |
guard let data = data, let result = String(data: data, encoding: .utf8) else { return } | |
var parameters: [String : String] = [:] | |
var par: [[String : String]] = [] | |
// 動画URL抽出 | |
for keyValue in result.split(separator: "&") { | |
let keyValueArray = keyValue.split(separator: "=") | |
guard let key = keyValueArray.first, let value = keyValueArray.last?.removingPercentEncoding else { continue } | |
if key == "url_encoded_fmt_stream_map" { | |
for child in value.split(separator: ",") { | |
var parameters2: [String : String] = [:] | |
for item in child.split(separator: "&") { | |
let keyValueArray2 = item.split(separator: "=") | |
guard let key2 = keyValueArray2.first, let value2 = keyValueArray2.last?.removingPercentEncoding else { continue } | |
parameters2[String(key2)] = value2 | |
} | |
par.append(parameters2) | |
} | |
} | |
parameters[String(key)] = value | |
} | |
// 画質良いurlを返す | |
guard let dic = par.first(where: { $0["quality"] == "hd720" }), let url = dic["url"] else { return } | |
// print(url) | |
completion(url) | |
semaphore.signal() | |
}) | |
task.resume() | |
semaphore.wait() | |
} | |
for url in youtubeURLs { | |
getURL(url) { urlString in | |
print(urlString) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment