所以聽了@Larme 和@JoakimDanielson(非常感謝,伙計們!)我開始在 URLSessions 上做一些任務,以實際從 GitHub API 獲取我正在尋找的資料。
這里的最終目標是為存盤庫創建一個移動 GitHub 搜索應用程式。
我已經實作了本教程中的代碼:https : //blog.devgenius.io/how-to-make-http-requests-with-urlsession-in-swift-4dced0287d40
使用相關的 GitHub API URL。我的代碼如下所示:
import UIKit
class Repository: Codable {
let id: Int
let owner, name, full_name: String
enum CodingKeys: String, CodingKey {
case id = "id"
case owner, name, full_name
}
init(id: Int, owner: String, name: String, fullName: String) {
self.id = id
self.owner = owner
self.name = name
self.full_name = full_name
}
}
(...)
let session = URLSession.shared
let url = URL(string: "https://api.github.com/search/repositories?q=CoreData&per_page=20")!
let task = session.dataTask(with: url, completionHandler: { data, response, error in
// Check the response
print(response)
// Check if an error occured
if error != nil {
// HERE you can manage the error
print(error)
return
}
// Serialize the data into an object
do {
let json = try JSONDecoder().decode(Repository.self, from: data! )
//try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
} catch {
print("Error during JSON serialization: \(error.localizedDescription)")
print(String(describing:error))
}
})
task.resume()
}
}
完整的錯誤文本是:
keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))
我嘗試洗掉一些有此錯誤的值,但其他值仍然拋出相同的值,我使用了在 GitHub 檔案中可以找到的編碼鍵:https : //docs.github.com/en/rest/reference/search#search-存盤庫
請幫忙!
uj5u.com熱心網友回復:
首先你不需要CodingKeys和init方法。
其次,使用結構,而不是類。
如果要解碼必須從根物件開始的存盤庫,則存盤庫位于 key 的陣列中 items
struct Root : Decodable {
let items : [Repository]
}
struct Repository: Decodable {
let id: Int
let name, fullName: String
let owner : Owner
}
struct Owner : Decodable {
let login : String
}
另一個問題是它owner也是一個字典,它變成了另一個結構。
為了擺脫CodingKeys的添加.convertFromSnakeCase其戰略轉化 full_name成fullName。
let session = URLSession.shared
let url = URL(string: "https://api.github.com/search/repositories?q=CoreData&per_page=20")!
let task = session.dataTask(with: url) { data, response, error in
// Check the response
print(response)
// Check if an error occured
if let error = error {
// HERE you can manage the error
print(error)
return
}
// Serialize the data into an object
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let json = try decoder.decode(Root.self, from: data! )
print(json)
} catch {
print("Error during JSON serialization:", error)
}
}
task.resume()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/405337.html
標籤:
