Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Created February 17, 2023 06:45
Show Gist options
  • Select an option

  • Save sturdysturge/1329d56290d9b8f9556c8d8439e2829f to your computer and use it in GitHub Desktop.

Select an option

Save sturdysturge/1329d56290d9b8f9556c8d8439e2829f to your computer and use it in GitHub Desktop.
import Foundation
@available(iOS 16.0, *)
class ViewModel: ObservableObject {
let baseURL = URL(string: "https://www.googleapis.com/youtube/v3/search")!
let apiKey = "YOUR_GOOGLE_API_KEY"
@Published var search = ""
@Published var items: [Item] = []
@Published var selectedVideo: String? = nil
var url: URL {
baseURL.appending(queryItems: [
URLQueryItem(name: "part", value: "snippet"),
URLQueryItem(name: "type", value: "video"),
URLQueryItem(name: "videoEmbeddable", value: "true"),
URLQueryItem(name: "maxResults", value: "10"),
URLQueryItem(name: "q", value: search
.replacingOccurrences(of: " ", with: ",")),
URLQueryItem(name: "key", value: apiKey)
])
}
func performSearch() {
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data, let response = try? JSONDecoder()
.decode(YTResponse.self, from: data) else {
fatalError("Could not parse response")
}
DispatchQueue.main.async {
self.items = response.items ?? []
}
}
.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment