目標
- 訪問陣列中的字典
- 一些如何在不手動編碼每個股票名稱的情況下解碼所有 1957 年的字典。
下圖是來自
在此處回答的另一個問題的幫助下,我在下面包含了我正在嘗試更改以實作上述目標的代碼。
CallApi.swift - 此檔案呼叫 API 并將其建模為 PriceApiModel
import UIKit
class ViewController: UIViewController {
let headers = [
"X-RapidAPI-Key": "Sorry I cannot include this",
"X-RapidAPI-Host": "binance43.p.rapidapi.com"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://binance43.p.rapidapi.com/ticker/price")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
func getData() {
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print("error")
} else {
let httpResponse = response as? HTTPURLResponse
do {
//let dictionary = try JSONSerialization.jsonObject(with: data!, options: [])
let model = try JSONDecoder().decode(PriceApiModel.self, from: data!)
//print(String(model.symbol) "name") // please see output below
//print(dictionary)
} catch {
print("NOT WORKING ")
}
}
})
dataTask.resume()
}
}
PriceApiModel.swift - 我試圖找到一種方法讓這個檔案成為解碼資料的模型
struct PriceApiModel: Hashable, Codable {
//changed the String type to Decimal
var price: String
// every property you are interested to decode needs a CodingKey.
// You can omit values you are not interested in
enum CodingKeys: CodingKey{
case askPrice
}
// here you decode your data into the struct
init(from decoder: Decoder) throws {
// get the container
let container = try decoder.container(keyedBy: CodingKeys.self)
// decode the askPrice into a String and cast it into a Decimal
let askPrice = String(try container.decode(String.self, forKey: .askPrice))
// check if casting was succesfull else throw
guard let askPrice = askPrice else{
throw CustomError.decodingError
}
// assign it
self.askPrice = askPrice
}
}
uj5u.com熱心網友回復:
所以我只是嘗試了你想要在這里實作的目標。首先,您通過繼承 a 將服務類(獲取資料)宣告為 ViewController UIViewController。在我看來,只是在課堂上使用它有點奇怪,因為UIViewController沒有使用。其次,我建議您觀看或閱讀有關Codable例如Hackingforswift的內容。它至少幫助了我:)
但是,這是一個代碼,它向您展示了它的作業方式:
OptionalObject由于資料結構的原因,需要將所有內容保存在陣列中。
struct OptionalObject<Base: Decodable>: Decodable {
public let value: Base?
public init(from decoder: Decoder) throws {
do {
let container = try decoder.singleValueContainer()
self.value = try container.decode(Base.self)
} catch {
self.value = nil
}
}
}
struct PriceApiModel: Codable {
let price: String
let symbol: String
}
class Service {
let headers = [
"X-RapidAPI-Key": "",
"X-RapidAPI-Host": "binance43.p.rapidapi.com"
]
let request = NSMutableURLRequest(
url: URL(string: "https://binance43.p.rapidapi.com/ticker/price")!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 5.0
)
init() {
self.getData()
}
func getData() {
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if let data = data {
let model = try? JSONDecoder().decode([OptionalObject<PriceApiModel>].self, from: data)
print(model?.compactMap { $0.value?.price })
print(model?.compactMap { $0.value?.symbol })
}
})
dataTask.resume()
}
}
希望我能幫上忙。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522250.html
標籤:json迅速代码解码
上一篇:iOSSwift-一次可以啟用多少個UILongPressGestureRecognizers?
下一篇:檢測按鈕組的onChange
