Skip to content

Instantly share code, notes, and snippets.

@tuhuynh27
Last active March 11, 2024 10:04
Show Gist options
  • Save tuhuynh27/768c0e55a8437de9683319a86608e7bc to your computer and use it in GitHub Desktop.
Save tuhuynh27/768c0e55a8437de9683319a86608e7bc to your computer and use it in GitHub Desktop.
cryptoBar
import Cocoa
import SwiftUI
class StatusBarController {
private var statusItem: NSStatusItem?
private var btcPrice: String = "Loading..."
private let binanceAPIURL = URL(string: "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT")!
init() {
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
self.statusItem = statusItem
statusItem.button?.title = "BTC Price: \(btcPrice)"
fetchData()
}
private func fetchData() {
URLSession.shared.dataTask(with: binanceAPIURL) { data, response, error in
guard let data = data else {
print("Error: \(error?.localizedDescription ?? "Unknown error")")
return
}
if let btcData = try? JSONDecoder().decode(BTCData.self, from: data) {
DispatchQueue.main.async {
self.btcPrice = btcData.price
self.statusItem?.button?.title = "BTC Price: \(self.btcPrice)"
}
}
}.resume()
}
}
struct ContentView: View {
var body: some View {
BTCStatusBarView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct BTCStatusBarView: NSViewRepresentable {
typealias NSViewType = NSView
func makeNSView(context: Context) -> NSView {
let _ = StatusBarController() // Ignoring the returned value
return NSView()
}
func updateNSView(_ nsView: NSView, context: Context) {
// Nothing to update
}
}
struct BTCData: Codable {
let price: String
enum CodingKeys: String, CodingKey {
case price = "price"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment