我正在嘗試使用組合框架決議來自網站 alphavantage.com 的股票資料。error Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"bestMatches\", intValue: nil) (\"bestMatches\").", underlyingError: nil))盡管我的資料模型具有與 json 匹配的正確值,但我一直得到這個。我該如何解決 ?
struct SearchResults: Decodable{
let bestMatches : [SearchResult]
enum CodingKeys: String, CodingKey{
case bestMatches = "bestMatches"
}
}
struct SearchResult : Decodable{
let symbol : String?
let name : String?
let type : String?
let currency :String?
enum CodingKeys:String, CodingKey{
case symbol = "1. symbol"
case name = "2. name"
case type = "3. type"
case currency = "8. currency"
}
}
struct APIservice{
let apiKey = "U893NJLDIREGERHB"
func fetchSymbols(keyword:String)-> AnyPublisher<SearchResults,Error>{
let urlSTring = "https://www.alphavantage.co/query?function=\(keyword)H&keywords=tesco&apikey=U893NJLDIREGERHB"
let url = URL(string: urlSTring)!
return URLSession.shared.dataTaskPublisher(for: url)
.map({$0.data})
.decode(type: SearchResults.self, decoder: JSONDecoder())
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}
func performSearch(){
apiSerivice.fetchSymbols(keyword: "S&P500").sink { (completion) in
switch completion {
case .failure(let error):
print(error)
case . finished:
break
}
} receiveValue: { (SearchResults) in
print(SearchResults.bestMatches)
}.store(in: &subcribers)
uj5u.com熱心網友回復:
您的查詢不正確。檢查符號搜索的檔案,您的 URL 必須傳入以SYMBOL_SEARCH進行function查詢。
您對關鍵字的查詢也沒有按照應有的方式進行 URL 編碼,因此"S&P 500"存在在插入字串時創建無效查詢的問題。更好的方法是使用,URLComponents以便安全地為您處理。
代碼:
func fetchSymbols(keyword: String) -> AnyPublisher<SearchResults, Error> {
guard var components = URLComponents(string: "https://www.alphavantage.co/query") else {
return Fail(
outputType: SearchResults.self,
failure: APIError.invalidComponents
).eraseToAnyPublisher()
}
components.queryItems = [
URLQueryItem(name: "function", value: "SYMBOL_SEARCH"),
URLQueryItem(name: "keywords", value: keyword),
URLQueryItem(name: "apikey", value: apiKey)
]
guard let url = components.url else {
return Fail(
outputType: SearchResults.self,
failure: APIError.invalidURL
).eraseToAnyPublisher()
}
return URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: SearchResults.self, decoder: JSONDecoder())
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
enum APIError: Error {
case invalidComponents
case invalidURL
}
我將查詢從 更改"S&P500"為"S&P 500",否則沒有結果。您也可以洗掉多余的內容CodingKeys,SearchResults因為這沒有任何效果。
注意:不要暴露您的 API 密鑰!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367036.html
上一篇:在型別級別實作JSON反序列化
