每次我尝试将swiftview或导航视图添加到swiftui代码时,都会导致该应用程序无法从api加载任何内容。目前,我正在使用OMDB API。粘贴的是我的电影商店和ContentView。目前,我正在使用自定义卡片视图来显示电影商店中的图像和标题,但是在尝试启用滚动视图后,呈现的应用程序的整个预览将完全变为白色。在我注释掉滚动视图之前,什么也不会再次显示。我尝试使用水平视图以及简单的图像和文本vstack来查看卡片视图是否以某种方式将滚动视图弄乱了。
为达到这一目的而进行一些修改后所遵循的教程位于:https://www.youtube.com/watch?v=NvyAN81YcO0
当前我正在运行Xcode 11.6。
import Foundation
struct MovieResponse : Decodable{
let movies: [Movie]
private enum CodingKeys:String, CodingKey{
case movies = "Search"
}
}
struct Movie: Decodable{
let imdbID :String
let title: String
let poster: String
let type: String
let year: String
private enum CodingKeys: String, CodingKey{
case imdbID
case title = "Title"
case poster = "Poster"
case type = "Type"
case year = "Year"
}
}
class MovieStore: ObservableObject{
@Published var movies: [Movie]? = [Movie]()
func getAll(){
guard let url = URL(string: "") else{
fatalError("Invalid url")
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else{
return
}
let movieResponse = try? JSONDecoder().decode(MovieResponse.self, from:data)
if let movieResponse = movieResponse {
DispatchQueue.main.async{
self.movies = movieResponse.movies
}
}
}.resume()
}
}
import SwiftUI
struct CardView: View {
var image: URLImage
var type: String
var title: String
var year: String
var body: some View {
VStack {
image
.aspectRatio(contentMode: .fit)
HStack {
VStack(alignment: .leading) {
Text(type)
.font(.headline)
.foregroundColor(.secondary)
Text(title)
.font(.title)
.fontWeight(.black)
.foregroundColor(.primary)
.lineLimit(3)
Text(year)
.font(.caption)
.foregroundColor(.secondary)
}
.layoutPriority(100)
Spacer()
}
.padding()
}
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color(.sRGB, red: 150/255, green: 150/255, blue: 150/255, opacity: 0.1), lineWidth: 1)
)
.padding([.top, .horizontal])
}
}
struct ContentView: View {
@ObservedObject var store: MovieStore
var body: some View {
// ScrollView{
HStack{
ForEach(store.movies ?? [Movie](), id: \.imdbID){ movie in
VStack{
// URLImage(url: movie.poster)
// .frame(width: 100, height: 150)
// Text(movie.title)
// .frame(maxHeight: .infinity, alignment: .top)
CardView(image: URLImage(url:movie.poster), type: movie.type, title: movie.title, year: movie.year)
}
}
}
// }
.onAppear(){
self.store.getAll()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(store: MovieStore())
}
}
编辑:
我能够通过滚动从api弹出的电影来生成应用程序。但仅具有list属性。我注意到我遇到了错误,并且不确定是否会影响api的ping操作。
2020-08-01 18:28:26.274953-0500 Nyx[19421:1105938] Task <B38BF736-765C-4C69-9ADE-AD889ED7BBE5>.<4> finished with error [-1002] Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x600003c14000 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, NSErrorFailingURLStringKey=N/A, NSErrorFailingURLKey=N/A, NSLocalizedDescription=unsupported URL}