使用 api 運行代碼時出現上述錯誤。我仔細檢查了復制 json 檔案并在本地運行它它作業正常,我似乎無法找到錯誤的來源,
國家.swift
struct APIResult: Codable {
var data: APICountryData
}
struct APICountryData: Codable {
var count: Int
var results: [Countries]
}
struct Countries: Identifiable, Codable {
var id: String
var name: String
var abrname: String
var flag_url: URL
var info: String
}
國家視圖模型.swift
class CountriesViewModel: ObservableObject {
@Published var searchQuery = ""
var searchCancellable: AnyCancellable? = nil
//Fetched Data....
@Published var fetchCountries: [Countries]? = nil
@Published var offset: Int = 0
init() {
searchCancellable = $searchQuery
.removeDuplicates()
.debounce(for: 0.6, scheduler: RunLoop.main)
.sink(receiveValue: { str in
if str == ""{
// reset Data...
self.fetchCountries = nil
} else {
//search Data...
self.searchCountry()
}
})
}
func searchCountry() {
let url = "my api url"
let session = URLSession(configuration: .default)
session.dataTask(with: URL(string: url)!) { (data, _, err) in
if let error = err{
print(error.localizedDescription)
return
}
guard let APIData = data else {
print("No Data found")
return
}
do {
// Decoding API Data....
let countrys = try JSONDecoder().decode(APIResult.self, from: APIData)
DispatchQueue.main.async {
if self.fetchCountries == nil {
self.fetchCountries = countrys.data.results
}
}
}
catch{
print(error.localizedDescription)
}
}
.resume()
}
}
當我在模擬器上測驗它運行時,但是當我搜索它時會出現這個錯誤“無法讀取資料,因為它的格式不正確。”
我的 json 資料示例
[
{
"id" : "0",
"name" : "Afghanistan",
"abrname" : "AFG",
"flag_url" : "Image URL",
"info" : "Afghanistan (/?|f??é??|néast?|n, ?|f??é?é‘?néasté‘?n/ (About this soundlisten);[23] Pashto/Dari: ?§ù?o?§ù??3?a?§ù? Af???nest?n, Pashto pronunciation: [afé£é‘néasté‘n], Dari pronunciation: [afé£é’?néasté’?n]), officially the Islamic Emirate of Afghanistan, is a landlocked country at the crossroads of Central and South Asia. It is bordered by Pakistan to the east and south, Iran to the west, Turkmenistan and Uzbekistan to the north, and Tajikistan and China to the northeast. Occupying 652,864 square kilometres (252,072 sq mi), the country is predominately mountainous with plains in the north and the southwest that are separated by the Hindu Kush mountains. Its population as of 2020 is 31.4 million, composed mostly of ethnic Pashtuns, Tajiks, Hazaras, and Uzbeks. Kabul serves as its capital and largest city."
},
{
"id" : "1",
"name" : "Andorra",
"abrname" : "AND",
"flag_url" : "Image URL",
"info" : "Andorra[g], officially the Principality of Andorra,[1][h] is a sovereign landlocked microstate on the Iberian Peninsula, in the eastern Pyrenees, bordered by France to the north and Spain to the south. Believed to have been created by Charlemagne, Andorra was ruled by the count of Urgell until 988, when it was transferred to the Roman Catholic Diocese of Urgell. The present principality was formed by a charter in 1278. It is headed by two co-princes: the Bishop of Urgell in Catalonia, Spain and the President of France. Its capital and also its largest city is Andorra la Vella. "
}
]
uj5u.com熱心網友回復:
你的設計是錯誤的。
代替
let countrys = try JSONDecoder().decode(APIResult.self, from: APIData)
DispatchQueue.main.async {
if self.fetchCountries == nil {
self.fetchCountries = countrys.data.results
}
}
和
let countries = try JSONDecoder().decode([Countries].self, from: APIData)
DispatchQueue.main.async {
self.fetchCountries = countries
}
其他兩個結構沒有意義。
并宣告fetchCountries為非可選空陣列并以單數形式命名結構Country。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/318425.html
