Created
August 21, 2021 12:57
-
-
Save dankamel/0ca0d3c38d06e4ed0f90aef3f6b71843 to your computer and use it in GitHub Desktop.
SwiftUI API Call $CLOUT Exchange Rate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct Exchange: Decodable, Hashable { | |
var BuyBitCloutFeeBasisPoints: Int? | |
var NanosSold: Int? | |
var SatoshisPerBitCloutExchangeRate: Int? | |
var USDCentsPerBitCloutExchangeRate: Int? | |
var USDCentsPerBitCloutReserveExchangeRate: Int? | |
var USDCentsPerBitcoinExchangeRate: Int? | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
class GetExchangeRate: ObservableObject { | |
func loadData(completion: @escaping (Exchange) -> ()) { | |
var exchangeRequest = URLRequest(url: URL(string: "https://bitclout.com/api/v0/get-exchange-rate")!,timeoutInterval: Double.infinity) | |
exchangeRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") | |
exchangeRequest.httpMethod = "GET" | |
let exchangeTask = URLSession.shared.dataTask(with: exchangeRequest) { (responseData, response, error) in | |
print(error) | |
print(response) | |
print(responseData) | |
if let resData = responseData { | |
let decoder = JSONDecoder() | |
do { | |
let finalData = try decoder.decode(Exchange.self, from: resData) | |
print(finalData.USDCentsPerBitCloutExchangeRate) | |
DispatchQueue.main.async { | |
completion(finalData) | |
} | |
} catch (let error) { | |
print(error) | |
} | |
} | |
} | |
exchangeTask.resume() | |
} | |
} | |
//Testing -- pulling API data into view | |
struct GetExchangeRateView: View { | |
@State var cloutPrice = Exchange() | |
var body: some View { | |
VStack { | |
Text(String(cloutPrice.USDCentsPerBitCloutExchangeRate ?? 0)) | |
}.onAppear() { | |
GetExchangeRate().loadData { (cloutPrice) in | |
self.cloutPrice = cloutPrice | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment