将来自API的解码数据用于算法

问题描述 投票:0回答:2

我成功地从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],...?

swift algorithm api
2个回答
1
投票

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

只是取消注释这条线completion(marketData, nil)

并在

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

items是你的struct 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()
        }

2
投票

您的数据将在您的fecthData()电话中提供。可能你想要的是你的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!")
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.