SwiftUI编码较新,似乎无法弄清楚整个初始化器的事情。当我把一个变量放到我的API调用中时,我一直得到这个错误。我试图让TextField的值成为API调用的术语。这是使用CatalogueRequest访问MusicKit。当您手动向请求中输入名称而不是任何变量时,它可以工作。任何帮助将不胜感激!
import SwiftUI
import MusicKit
struct SearchView: View {
@State var songs = [songInfo]()
@State var searchQuery = ""
var body: some View {
VStack {
TextField("Search", text: $searchQuery,
onCommit: {
fetchMusic()
})
.padding()
NavigationView {
List(songs) { song in
HStack {
AsyncImage(url: song.imageURL)
.frame(width: 75, height: 75, alignment: .center)
VStack(alignment: .leading) {
Text(song.name)
.font(.title3)
Text(song.artist)
.font(.footnote)
}
.padding()
}
}
}
.onAppear {
fetchMusic()
}
}
}
private let request: MusicCatalogSearchRequest = {
var request = MusicCatalogSearchRequest(term: "Cruel Summer", types: [Song.self])
request.limit = 25
return request
}()
private func fetchMusic() {
Task {
//Request permission
let status = await MusicAuthorization.request()
switch status {
case .authorized:
do {
let result = try await request.response()
self.songs = result.songs.compactMap({
return .init(name: $0.title,
artist: $0.artistName,
artworkColor: $0.artwork?.backgroundColor,
imageURL: $0.artwork?.url(width: 75, height: 75),
imageURLSmall: $0.artwork?.url(width: 256, height: 256),
imageURLLarge: $0.artwork?.url(width: 1028, height: 1028))
})
print(String(describing: songs[0]))
} catch {
print(String(describing: error))
}
default: break
}
}
}
}
#Preview {
SearchView()
}
我尝试过手动初始化,显式地将其定义为字符串,并不断得到越来越多的错误。
1条答案
按热度按时间k5ifujac1#
我看不到
request
属性在fetchMusic
函数之外的任何地方被使用,所以我将它作为该函数内部的局部变量。