【发布时间】:2021-09-28 04:29:20
【问题描述】:
我正在制作这个应用程序,它会显示有关即将上映的动漫的某些信息,我为此使用 jikan API,它不需要任何身份验证或任何密钥
这是 API 的外观 -
{
"request_hash": "request:top:3506eaba6445f7ad5cc2f78417bf6ed916b6aaad",
"request_cached": true,
"request_cache_expiry": 43675,
"top": [
{
"mal_id": 40356,
"rank": 1,
"title": "Tate no Yuusha no Nariagari Season 2",
"url": "https://myanimelist.net/anime/40356/Tate_no_Yuusha_no_Nariagari_Season_2",
"image_url": "https://cdn.myanimelist.net/images/anime/1245/111800.jpg?s=7302aaeb3bc4e1433b32d094e9d6f6f0",
"type": "TV",
"episodes": {},
"start_date": "Apr 2022",
"end_date": {},
"members": 300837,
"score": 0
},
{
"mal_id": 48583,
"rank": 2,
"title": "Shingeki no Kyojin: The Final Season Part 2",
"url": "https://myanimelist.net/anime/48583/Shingeki_no_Kyojin__The_Final_Season_Part_2",
"image_url": "https://cdn.myanimelist.net/images/anime/1989/116577.jpg?s=f6312bda2e67f86595936d0264696a91",
"type": "TV",
"episodes": {},
"start_date": "Jan 2022",
"end_date": {},
"members": 253849,
"score": 0
},
这就是我编写代码的方式,由于某种原因,当我运行应用程序时,我只是得到一个纯空白的白屏,并且它还打印出我添加的最后一个打印语句,上面写着“Fetch Failed: Unknown error” 请帮我解决这个问题
import SwiftUI
struct Response: Codable{
var top: [Result]
}
struct Result: Codable {
var mal_id: Int
var rank: Int
var title: String
var type: String
var start_date: String
}
struct ContentView: View {
func loadData() {
guard let url = URL(string: "https://api.jikan.moe/v3/top/anime/1/upcoming") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
// we have good data – go back to the main thread
DispatchQueue.main.async {
// update our UI
self.top = decodedResponse.top
}
// everything is good, so we can exit
return
}
}
// if we're still here it means there was a problem
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
@State private var top = [Result]()
var body: some View {
ScrollView {
List(top, id: \.mal_id) { item in
VStack(alignment: .leading) {
Text(item.title)
.font(.headline)
Text(String("\(item.rank)"))
.font(.headline)
Text(item.type)
.font(.headline)
Text(item.start_date)
.font(.headline)
}
}
}
.onAppear(perform: loadData)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
【问题讨论】:
-
不要
try?。您忽略了一个可能的且非常具有描述性的错误。在catch子句中将try?替换为try和do - catch块和print(error) -
感谢您的帮助,现在已经解决了,当我按照您告诉我的操作时,它抛出了一个错误提示。 " 从抛出函数类型 '(Data?, URLResponse?, Error?) throws -> Void' 到非抛出函数类型 '(Data?, URLResponse?, Error?) -> Void' 的无效转换”
-
所以我只是选择了另一个解决方案,现在它可以工作了
-
正如我所说你必须写
do { let decodedResponse = try .... } catch { print(error) }