Code 88

Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 5

/*

{
"name": "Fear and Greed Index",
"data": [
{
"value": "52",
"value_classification": "Neutral",
"timestamp": "1641792000",
"time_until_update": "47649"
},
{
"value": "60",
"value_classification": "Greed",
"timestamp": "1641705600",
"time_until_update": "129649"
}
],
"metadata": {
"error": null
}
}
*/

import SwiftUI
import Foundation
import Combine

@main
struct GreedFearAppApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

//struct FearGreedData: Codable, Identifiable {


// let id = UUID() // Unique identifier for
SwiftUI lists
// let value: String
// let value_classification: String
// let timestamp: String
// let time_until_update: String
//}

struct ToDo: Codable, Identifiable {


let userId: Int
let id = UUID()
let title: String
let body: String
}

// Model for the full API response


//struct FearGreedResponse: Codable {
// let name: String
// let data: [FearGreedData]
// let metadata: FearGreedMetadata
//}

//struct FearGreedMetadata: Codable {


// let error: String?
//}

class FearGreedService: ObservableObject {


var fearGreedData: ToDo = ToDo(userId:
23, title: "sdfs", body: "sfsf") // Publish data to
SwiftUI views

private var cancellables =


Set<AnyCancellable>()

// Fetch data from the API


func fetchFearGreedData() {
guard let url = URL(string:
"https://jsonplaceholder.typicode.com/posts/1"
) else {
print("Invalid URL")
return
}

URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: ToDo.self, decoder:
JSONDecoder())
.receive(on: DispatchQueue.main)
// Update on the main thread
.sink(receiveCompletion:
{ completion in
switch completion {
case .failure(let error):
print("Error fetching data: \
(error)")
case .finished:
break
}
}, receiveValue: { [weak self]
response in
self?.fearGreedData =
response // Update the published data
})
.store(in: &cancellables)
}
}

struct ContentView: View {


@StateObject private var fearGreedService
= FearGreedService() // The networking
service

var body: some View {


NavigationView {
VStack {
if
fearGreedService.fearGreedData != nil {
Text("Loading...") // Show a
loading text while data is being fetched
.onAppear {

fearGreedService.fetchFearGreedData()
VStack(alignment: .leading) {
Text("Value: \
(fearGreedService.fearGreedData.title)")

.font(.headline)

Text("Classification: \
(fearGreedService.fearGreedData.title)")

.font(.subheadline)

Text("Timestamp: \
(fearGreedService.fearGreedData.title)")

.font(.caption)
}// Fetch data when
view appears
}
} else {

You might also like