2021-06-11 12:36:26 +00:00
|
|
|
import Foundation
|
|
|
|
import SwiftyJSON
|
|
|
|
|
2021-06-14 18:05:02 +00:00
|
|
|
final class SearchedVideosProvider: DataProvider {
|
2021-06-11 12:36:26 +00:00
|
|
|
@Published var videos = [Video]()
|
2021-06-11 21:11:59 +00:00
|
|
|
|
2021-06-14 18:05:02 +00:00
|
|
|
var currentQuery: String = ""
|
2021-06-11 12:36:26 +00:00
|
|
|
|
2021-06-14 18:05:02 +00:00
|
|
|
func load(_ query: String) {
|
|
|
|
var newQuery = query
|
|
|
|
|
|
|
|
if let url = URLComponents(string: query),
|
|
|
|
let queryItem = url.queryItems?.first(where: { item in item.name == "v" }),
|
|
|
|
let id = queryItem.value
|
|
|
|
{
|
|
|
|
newQuery = id
|
|
|
|
}
|
|
|
|
|
|
|
|
if newQuery == currentQuery {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
currentQuery = newQuery
|
|
|
|
|
|
|
|
let searchPath = "search?q=\(currentQuery.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!)"
|
2021-06-11 12:36:26 +00:00
|
|
|
DataProvider.request(searchPath).responseJSON { response in
|
|
|
|
switch response.result {
|
|
|
|
case let .success(value):
|
|
|
|
self.videos = JSON(value).arrayValue.map { Video($0) }
|
|
|
|
case let .failure(error):
|
|
|
|
print(error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|