Skip to content

Instantly share code, notes, and snippets.

@erdemildiz
Last active March 9, 2022 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erdemildiz/821fa1f0ab67fed22b4091a5aa19d151 to your computer and use it in GitHub Desktop.
Save erdemildiz/821fa1f0ab67fed22b4091a5aa19d151 to your computer and use it in GitHub Desktop.
//
// ContentView.swift
// socket-demo
//
// Created by Erdem ILDIZ
//
import SwiftUI
import SocketIO
enum SocketConfig {
static let url = "http://localhost:5000"
}
struct ContentView: View {
@State var currencyList: [CurrencyItem] = []
let socketManager = SocketManager(
socketURL: URL(string: SocketConfig.url)!,
config: [.log(true), .compress])
var body: some View {
NavigationView {
List {
ForEach(currencyList, id: \.id) { currency in
HStack {
Text(currency.name)
.font(.system(size: 16))
Spacer()
Text(currencyFormatting(price: currency.quote.price.priceValue))
.foregroundColor(.black)
.font(.system(size: 16, weight: .bold, design: .default))
}
}
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("Currency List")
}
.onAppear {
setupSocketConnection()
}
}
}
extension ContentView {
private func setupSocketConnection() {
// 1
let socket = socketManager.defaultSocket
// 2
socket.on(clientEvent: .connect) { data, ack in
socket.on("fetched-currency-list") { data, ack in
guard let receicedData = data[0] as? NSMutableDictionary,
let list = receicedData.object(forKey: "list") as? NSDictionary else {
return
}
// Decode received response
do {
// 3
let listData = try JSONSerialization.data(withJSONObject: list, options: .prettyPrinted)
let currencyData = try JSONDecoder().decode(CurrencyList.self, from: listData)
self.currencyList = currencyData.data
} catch{
print(error.localizedDescription)
}
// 3
// Fetch currency list every minute
Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { _ in
socket.emit("get-new-currency-list", with: [])
}
}
}
// 4
socket.connect()
}
// 5
private func currencyFormatting(price: Double) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
if let str = formatter.string(for: price) {
return str
}
return ""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment