swift 想弄明白为什么我的URL会话不起作用

piah890a  于 2024-01-05  发布在  Swift
关注(0)|答案(1)|浏览(139)

我目前正在学习Swift,并将一个应用程序重新创建为一个项目。我有这个API,我试图命中,但它只是不工作,* 有时 *。我在完成时放入断点,有时我会得到一个响应命中,但大多数时候我不会。错误返回nil btw。
APIService.swift

  1. import Foundation
  2. final class APIService {
  3. init(){}
  4. struct Constants{
  5. 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")
  6. }
  7. public func getListings(completion: @escaping (Result<[WindbnbListing], Error>) -> Void) {
  8. guard let url = Constants.apiURL else {
  9. return
  10. }
  11. let request = URLRequest(url: url)
  12. let task = URLSession.shared.dataTask(with: request) { data, _, error in
  13. guard let data = data, error == nil else {
  14. if let error {
  15. completion(.failure(error))
  16. }
  17. return
  18. }
  19. do{
  20. let response = try JSONDecoder().decode(WindbnbListingsResponse.self, from: data)
  21. completion(.success(response.results))
  22. }catch{
  23. let json = try? JSONSerialization.jsonObject(with: data)
  24. print(String(describing: json))
  25. completion(.failure(error))
  26. }
  27. }
  28. task.resume()
  29. }
  30. }

字符串
WindbnbListingsResponse.swift

  1. import Foundation
  2. struct WindbnbListingsResponse: Codable {
  3. let total_count: Int
  4. let results: [WindbnbListing]
  5. }


WindbnbListing.swift

  1. import Foundation
  2. struct WindbnbListing: Codable, Hashable, Identifiable {
  3. let id: String?
  4. let listing_url: String?
  5. let name: String?
  6. let summary: String?
  7. let space: String?
  8. let description: String?
  9. let house_rules: String?
  10. let thumbnail_url: String?
  11. let medium_url: String?
  12. let xl_picture_url: String?
  13. let neighborhood: String?
  14. let amenities: [String]?
  15. let price: Int?
  16. //Host info
  17. let host_name: String
  18. let host_since: String
  19. let host_thumbnail_url: String
  20. let host_picture_url: String
  21. }


这里是控制台输出的一瞥,当它以某种方式工作时.
控制台输出: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中,我可以一遍又一遍地发出请求,而不会出现任何问题

a0zr77ik

a0zr77ik1#

欢迎@workingdogsupportUkraine!
在您的WindbnbListing中,使所有属性都是可选的。也就是说,将?添加到host_name,host_since,host_thumbnail_url和host_picture_url。这样,您的代码对我来说就很好了。为了进一步调试您的代码,将print(“-> error:(error)”)添加到您的catch。- workingdog support Ukraine

相关问题