Swift:无法从闭包中的URLComponents获取URL

时间:2019-01-30 06:59:51

标签: swift closures nsurlcomponents

我正在尝试创建一个URL,并从一个闭包内部存储字符串表示形式。使用URLSession访问一些JSON之后,我创建另一个URL(使用URLComponents)以存储在模型中的对象中。

但是,我的网址不断意外返回nil,并且使guard语句失败,从而触发了preconditionFailure(message:)子句。

我可以验证我的URLComponents对象(artistComponents)不是nil。我试图在闭包内创建一个新的URLComponents对象,并从闭包内引用一个URLComponents类属性,该属性表示必要的url信息。

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
}

我正在寻找验证URL,以便可以将该对象添加到我的数据模型中。有什么建议吗?预先谢谢你!

0 个答案:

没有答案