结合URLSession和Json解码器AlphaVantage概述数据

问题描述

我正在尝试通过合并,URLSession和解码来获取AlphaVantage库存数据。我使用了如下框架。我使用相同的框架成功获取了其他AlphaVantage数据,例如损益表和现金流量。但是它不适用于概述数据。我找不到问题所在。我已经为此苦苦挣扎了一段时间,非常感谢有人能帮忙。

import Foundation
import Combine

var subscriptions = Set<AnyCancellable>()


let pub1 = getCompOverview()
    .sink(receiveCompletion: { completion in
        switch completion {
        case .finished:
            print(".sink completed")
            break
        case .failure(let anError):
            print("received error: ",anError)
        }
    },receiveValue: { receivedValue in
        print(".sink() received \(receivedValue)")
    })
    .store(in: &subscriptions)

func getCompOverview() -> AnyPublisher<CompOverview,Error> {
    guard let url = URL(string: "https://www.alphavantage.co/query?function=OVERVIEW&symbol=IBM&apikey=demo") else {
        return Fail(error: FetchError.invalidURL).eraseToAnyPublisher()
    }
    return URLSession.shared.dataTaskPublisher(for: url)
        .retry(2)
        .tryMap { data,response in
            guard
                let httpURLResponse = response as? HTTPURLResponse,httpURLResponse.statusCode == 200
            else {
                throw URLError(.badServerResponse)
            }
            print("fetching data size = \(data)")
            return data
        }
        .decode(type: CompOverview.self,decoder: JSONDecoder())
        .receive(on: RunLoop.main)
        .eraseToAnyPublisher()
}


struct CompOverview: Codable {
    var symbol:                 String
    var name:                   String
    var description:            String
    var sector:                 String
    var industry:               String
    
    var peRatio:                String
    var pegRatio:               String
    var forwardPE:              String
    var eps:                    String
    
    var divPerShare:       String
    var divYield:          String
    var payoutRatio:            String
    
    var percentInsiders:        String
    var percentInstitutions:    String
    
    var priceToSalesRatioTTM:   String
    var marketCapitalization:   String
    var sharesOutstanding:      String
    
    enum CodingKeys: String,CodingKey {
        case symbol = "Symbol"
        case name = "Name"
        case description = "Description"
        case sector = "Sector"
        case industry = "Industry"
        case peRatio = "PERatio"
        case pegRatio = "PEGRatio"
        case forwardPE = "ForwardPE"
        case eps = "EPS"
        
        case divPerShare = "DividendPerShare"
        case divYield = "DividendYield"
        case payoutRatio = "PayoutRatio"
        
        case percentInsiders = "PercentInsiders"
        case percentInstitutions = "PercentInstitutions"
        
        case priceToSalesRatioTTM = "PriceToSalesRatioTTM"
        case marketCapitalization = "MarketCapitalization"
        case sharesOutstanding = "SharesOutstanding"
    }
    
}
enum FetchError: Error {
    case statusCode
    case decoding
    case invalidImage
    case invalidURL
    case other(Error)
    
    static func map(_ error: Error) -> FetchError {
        return (error as? FetchError) ?? .other(error)
    }

当我在操场上测试代码时。它将行打印在.tryMap闭包中。但是,.sink没有执行。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...