view LazyBear/Views/Profile/Networking/ProfileData.swift @ 343:ab909fc9ce55

Implement batch requests HomeView
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Tue, 06 Apr 2021 11:04:21 +0200
parents
children fde2b30c719e
line wrap: on
line source

//
//  ProfileData.swift
//  LazyBear
//
//  Created by Dennis Concepción Martín on 5/4/21.
//

import SwiftUI

class ProfileData: ObservableObject {
    @Published var companies = [CompanyQuoteModel]()
    @Published var showView = false
    @FetchRequest(entity: WatchlistCompany.entity(), sortDescriptors: [])
    var watchlistCompanies: FetchedResults<WatchlistCompany>
    
    private let baseUrl = Bundle.main.infoDictionary?["IEX_URL"] as? String ?? "Empty url"
    private let apiKey = Bundle.main.infoDictionary?["IEX_API"] as? String ?? "Empty key"
    
    private func get() {
        var url = "\(baseUrl)/stock/market/batch?symbols="
        
        if !watchlistCompanies.isEmpty {
            let symbols = watchlistCompanies.map { $0.symbol }
            for symbol in symbols {
                if symbols.firstIndex(of: symbol) == 0 {
                    url += symbol!
                } else {
                    url += "\(symbol!),"
                }
            }
            
            url = "&types=quote&token=\(apiKey)"
            genericRequest(url: url, model: [String: CompanyQuoteBatch].self) {
                print($0)
                self.showView = true
            }
        } else {
            self.showView = true
        }
    }
}


struct CompanyQuoteBatch: Codable {
    var quote: CompanyQuoteModel
}