我目前正在学习Swift,并将一个应用程序重新创建为一个项目。我有这个API,我试图命中,但它只是不工作,* 有时 *。我在完成时放入断点,有时我会得到一个响应命中,但大多数时候我不会。错误返回nil btw。
APIService.swift
import Foundation
final class APIService {
init(){}
struct Constants{
static let apiURL = URL(string: "https://public.opendatasoft.com/api/explore/v2.1/catalog/datasets/airbnb-listings/records?limit=100&refine=city%3A%22New%20York%22&refine=room_type%3A%22Entire%20home%2Fapt%22")
}
public func getListings(completion: @escaping (Result<[WindbnbListing], Error>) -> Void) {
guard let url = Constants.apiURL else {
return
}
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data, error == nil else {
if let error {
completion(.failure(error))
}
return
}
do{
let response = try JSONDecoder().decode(WindbnbListingsResponse.self, from: data)
completion(.success(response.results))
}catch{
let json = try? JSONSerialization.jsonObject(with: data)
print(String(describing: json))
completion(.failure(error))
}
}
task.resume()
}
}
字符串
WindbnbListingsResponse.swift
import Foundation
struct WindbnbListingsResponse: Codable {
let total_count: Int
let results: [WindbnbListing]
}
型
WindbnbListing.swift
import Foundation
struct WindbnbListing: Codable, Hashable, Identifiable {
let id: String?
let listing_url: String?
let name: String?
let summary: String?
let space: String?
let description: String?
let house_rules: String?
let thumbnail_url: String?
let medium_url: String?
let xl_picture_url: String?
let neighborhood: String?
let amenities: [String]?
let price: Int?
//Host info
let host_name: String
let host_since: String
let host_thumbnail_url: String
let host_picture_url: String
}
型
这里是控制台输出的一瞥,当它以某种方式工作时.
控制台输出:data Foundation.Data? 598105 bytes some _1 URLResponse? 0x0000600000266900 error Error? nil none completion () -> () 0x00000001023b047c Windbnb
partial apply forwarder for closure #1(Swift.Result<Swift.Array<Windbnb.WindbnbListing>,Swift.Error>)->()in Windbnb. WindbnbListingsViewModel.fetchListings()->()at data Foundation.Data 598105 bytes
response Windbnb.WindbnbListingsResponse `正如你所看到的,我有时会得到一个响应......这可能是一个端点问题,我的速率受到限制?怀疑,因为在postman中,我可以一遍又一遍地发出请求,而不会出现任何问题
1条答案
按热度按时间a0zr77ik1#
欢迎@workingdogsupportUkraine!
在您的WindbnbListing中,使所有属性都是可选的。也就是说,将?添加到host_name,host_since,host_thumbnail_url和host_picture_url。这样,您的代码对我来说就很好了。为了进一步调试您的代码,将print(“-> error:(error)”)添加到您的catch。- workingdog support Ukraine