0

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!

Jayesh Thanki
  • 1,879
  • 2
  • 21
  • 29
AUSTOOO
  • 41
  • 1
  • 9
  • What does `this.components.url!` resolve into? – pckill Jan 30 '19 at 09:07
  • @pckill this.components.url! resolves into a valid `URL` with expected output. It is a previous `URL` that I am using as the basis for the desired `URL` with modified path and queryItems properties. – AUSTOOO Jan 30 '19 at 11:11
  • @pckill You hit the nail on the head. Such a simple fix... Thank you for your time and assistance! – AUSTOOO Jan 30 '19 at 18:23

0 Answers0