微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决结合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 举报,一经查实,本站将立刻删除。