-
-
Save sturdysturge/1329d56290d9b8f9556c8d8439e2829f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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