将API中的解码数据用于算法

时间:2017-12-29 11:06:49

标签: swift algorithm api

我成功地从API获取并解码了数据,现在可以访问我想在我的应用程序中编写的算法中需要使用的所有数据。

问题是我解码后我不知道如何访问这些数据,我可以在解码后立即打印,但我不知道如何在其他功能或地方使用它在我的应用程序中。

这是我的游乐场:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

enum MyError : Error {
    case FoundNil(String)
}

struct Level: Codable {
    let time: Double
    let close: Double
    let high: Double
    let low: Double
    let open: Double
}

struct Response: Codable {
    let data: [Level]

    private enum CodingKeys : String, CodingKey {
        case data = "Data"
    }
}

func fetchData(completion: @escaping (Response?, Error?) -> Void) {
    let url = URL(string: "https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=3&e=CCCAGG")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        do {
            if let marketData = try? JSONDecoder().decode(Response.self, from: data) {
                print(marketData.data[0].open)
                print(marketData.data[1].open)
                print("Average=", (marketData.data[0].open + marketData.data[1].open) / 2)
                //completion(marketData, nil)
                throw MyError.FoundNil("data")
            }
        } catch {
            print(error)
        }
    }
    task.resume()
}

fetchData() { items, error in
    guard let items = items,
        error == nil else {
            print(error ?? "Unknown error")
            return
    }
    print(items)
}

如何在其他地方使用.data [0],。data [1],...?

2 个答案:

答案 0 :(得分:2)

您的items电话中将提供您的数据。您可能想要的是fetchData变量,您可以在其中进行打印。但请务必在import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true enum MyError: Error { case FoundNil(String) case DecodingData(Data) } struct Level: Codable { let time: Double let close: Double let high: Double let low: Double let open: Double } struct Response: Codable { let data: [Level] private enum CodingKeys : String, CodingKey { case data = "Data" } } func fetchData(completion: @escaping (Response?, Error?) -> Void) { let url = URL(string: "https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=3&e=CCCAGG")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { completion(nil, MyError.FoundNil("data")) } do { if let marketData = try? JSONDecoder().decode(Response.self, from: data) { completion(marketData, nil) } else { completion(nil, MyError.DecodingData(data)) // work on this duplicated call } } catch { completion(nil, MyError.DecodingData(data)) // work on this duplicated call } } task.resume() } fetchData() { items, error in if let error == error { switch(error) { case .foundNil(let whatsNil): print("Something is nil: \(whatsNil)") case .decodingData(let data): print("Error decoding: \(data)") } } else { if let items = items { print(items.data[0].open) print(items.data[1].open) print("Average=", (items.data[0].open + items.data[1].open) / 2) print(items) } else { print("No items to show!") } } } 实施中致电完成。

警告:未经测试的代码。

{{1}}

答案 1 :(得分:1)

我不明白你的真正问题是什么,因为你已经写下了你需要的所有内容,但据我所知,传递数据

取消注释此行completion(marketData, nil)

并在

fetchData() { items, error in
    guard let items = items,
        error == nil else {
            print(error ?? "Unknown error")
            return
    }
    print(items)
}

itemsstruct Response的一个对象。您可以通过创建另一个变量(例如:

)将其传递到其他class中的任何位置
var items : Response!

例如:

 class SomeOtherClass : NSObject{
    var items : Response!
func printSomeData()
{
 print(items.data[0].open)
 print(items.data[1].open)
 print("Average=", (items.data[0].open + items.data[1].open) / 2)
}
    }

并在fetchData方法中写下:

 fetchData() { items, error in
            guard let items = items,
                error == nil else {
                    print(error ?? "Unknown error")
                    return
            }
            let otherObject = SomeOtherClass()
    otherObject.items = items
otherObject.printSomeData()
        }