I'm trying to create a url and store the string representation from within a closure. After accessing some JSON using URLSession
, I create another url (using URLComponents
) to be stored within an object in my model.
However, my url keeps returning nil
unexpectedly, and fails the guard statement, triggering the preconditionFailure(message:)
clause.
I can verify that my URLComponents
object (artistComponents) is not nil
. I have tried to create a new URLComponents
object within the closure, as well as reference a URLComponents
class property from within the closure representing the necessary url information.
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let artistResponse = try decoder.decode(ArtistListResponse.self, from: data)
var artistComponents = URLComponents(url: this.components.url!, resolvingAgainstBaseURL: false)
// Have also tried:
// var artistComponents = this.components
// var artistComponents = URLComponents() and then proceed to fill in necessary information
artistComponents?.path = "generate"
for jsonArtist in artistResponse.data {
artistComponents?.queryItems = [URLQueryItem(name: "artist", value: jsonArtist.urlName)]
guard let artistURL = artistComponents?.url else {
preconditionFailure("Failed to construct artistURL for \(jsonArtist.name)")
}
let artist = Artist(id: this.idCount,
name: jsonArtist.name,
urlName: jsonArtist.urlName,
url: artistURL.absoluteString,
avatarURL: jsonArtist.avatarURL,
song: nil)
this.artists.append(artist)
this.idCount += 1
}
I'm looking to verify the url so I can add the object to my data model. Any advice? Thank you in advance!