Swiftui 无法读取数据,因为它的格式不正确
Swiftui The data couldn’t be read because it isn’t in the correct format
我在 运行 我的代码中使用 api 时出现上述错误。我仔细检查了复制 json 文件并 运行 在本地将其正常工作,我似乎无法了解错误的来源,
Countries.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
}
CountriesViewModel.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()
}
}
当我在模拟器上测试它时它 运行s,但是当我搜索它时它会出现这个错误“无法读取数据,因为它的格式不正确。”
我的 json 数据样本
[
{
"id" : "0",
"name" : "Afghanistan",
"abrname" : "AFG",
"flag_url" : "Image URL",
"info" : "Afghanistan (/æfˈɡænɪstæn, æfˈɡɑËnɪstÉ‘Ën/ (About this soundlisten);[23] Pashto/Dari: Ø§ÙØºØ§Ù†Ø³ØªØ§Ù† AfÄ¡ÄnestÄn, Pashto pronunciation: [afɣɑnɪstÉ‘n], Dari pronunciation: [afɣɒËnɪstÉ’Ë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. "
}
]
你的设计有误。
替换
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
.
我在 运行 我的代码中使用 api 时出现上述错误。我仔细检查了复制 json 文件并 运行 在本地将其正常工作,我似乎无法了解错误的来源,
Countries.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
}
CountriesViewModel.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()
}
}
当我在模拟器上测试它时它 运行s,但是当我搜索它时它会出现这个错误“无法读取数据,因为它的格式不正确。”
我的 json 数据样本
[
{
"id" : "0",
"name" : "Afghanistan",
"abrname" : "AFG",
"flag_url" : "Image URL",
"info" : "Afghanistan (/æfˈɡænɪstæn, æfˈɡɑËnɪstÉ‘Ën/ (About this soundlisten);[23] Pashto/Dari: Ø§ÙØºØ§Ù†Ø³ØªØ§Ù† AfÄ¡ÄnestÄn, Pashto pronunciation: [afɣɑnɪstÉ‘n], Dari pronunciation: [afɣɒËnɪstÉ’Ë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. "
}
]
你的设计有误。
替换
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
.