Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ViewModel : ObservableObject {
- @Published var searchedSongs = [SongDetails]()
- d
- @Published var apiResponse : APIResponse?
- @Published var lyricsHistory : SongDetails?
- @Published var apiError: APIError?
- func loadApiSongData2(songName : String, artistName : String) {
- let rawUrl = "https://api.lyrics.ovh/v1/\(artistName)/\(songName)"
- let fixedUrl = rawUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
- print("Old url: \(rawUrl)")
- print("New url: \(fixedUrl!)")
- guard let url = URL(string: fixedUrl!) else {
- print("Invalid URL")
- return
- }
- let request = URLRequest(url: url)
- URLSession.shared.dataTask(with: request) { data, response, error in
- DispatchQueue.main.async {
- self.responseHandler(data, response, error, songName, artistName)
- }
- }.resume()
- }
- private func responseHandler(_ data: Data?,
- _ response: URLResponse?,
- _ error: Error?,
- _ songName: String,
- _ artistName: String) {
- if let error = error {
- if error._code == -1009 {
- apiError = .offline
- } else {
- apiError = .sessionError
- }
- return
- }
- guard let response = response as? HTTPURLResponse, let data = data else {
- apiError = .missingDataError
- return
- }
- guard (200..<300).contains(response.statusCode) else {
- switch Status(rawValue: response.statusCode) {
- case .requestTimeout:
- apiError = .timeoutError
- case .internalServerError:
- apiError = .internalServerError
- case .notFound:
- apiError = .notFound
- default:
- apiError = .requestError
- }
- return
- }
- do {
- let decodedResponse = try JSONDecoder().decode(Song.self, from: data)
- if(!songAlreadySearched(songName: songName)) {
- let song = SongDetails(songName: songName, artistName: artistName, lyrics: decodedResponse.lyrics)
- searchedSongs.append(song)
- }
- apiResponse = APIResponse(apiValues: [decodedResponse.lyrics])
- } catch {
- apiError = .parsingError
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment