-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketViewController.swift
More file actions
84 lines (69 loc) · 2.83 KB
/
SocketViewController.swift
File metadata and controls
84 lines (69 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// SocketViewController.swift
// API_test
//
// Created by nick on 3/15/21.
//
import UIKit
import Starscream
class SocketViewController: UIViewController {
@IBOutlet weak var connectionButton: UIButton!
@IBOutlet weak var writeButton: UIButton!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var connectionLabel: UILabel!
@objc let priceSocket = PriceSocket()
var priceObservation: NSKeyValueObservation?
var tickerObservation: NSKeyValueObservation?
var tickerKVO: String?
override func viewDidLoad() {
super.viewDidLoad()
priceLabel.text = ""
print(UIDevice().name)
if UIDevice().name == "iPhone 8" {
connectionButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .regular)
} else {
connectionButton.titleLabel?.font = UIFont.systemFont(ofSize: 30, weight: .bold)
}
priceObservation = observe(\SocketViewController.priceSocket.currentPrice, options: [.new], changeHandler: { (vc, change) in
guard let updatedPrice = change.newValue else { return }
print("New price \(updatedPrice)")
self.priceLabel.text = "\(self.tickerKVO!) $\(String(updatedPrice))"
})
tickerObservation = observe(\SocketViewController.priceSocket.currentTicker, options: [.new], changeHandler: { (vc, change) in
guard let updatedTicker = change.newValue as? String else { return }
print("New ticker \(updatedTicker)")
self.tickerKVO = updatedTicker
})
priceSocket.createConnection()
}
@IBAction func connectButtonDidPressed(_ sender: UIButton) {
if priceSocket.isConnected {
connectionButton.setTitle("Connect", for: .normal)
priceSocket.webSocket.disconnect()
} else {
connectionButton.setTitle("Disconnect", for: .normal)
priceSocket.webSocket.connect()
}
}
@IBAction func writeButtonDidPressed(_ sender: UIButton) {
subscribe(symbol: "AAPL")
subscribe(symbol: "TSLA")
subscribe(symbol: "YNDX")
subscribe(symbol: "KO")
// subscribe(symbol: "BINANCE:BTCUSDT")
}
func subscribe(symbol: String) {
let json = ["type": "subscribe", "symbol": symbol]
let data = try! JSONEncoder().encode(json)
print("Subscribed at \(symbol)")
priceSocket.webSocket.write(data: data)
}
func updatePriceLabel(price: Float, ticker: String) {
// print(priceSocket.currentTicker)
// print(priceSocket.currentPrice)
print(price)
print(ticker)
priceLabel.text = "\(ticker) = \(price))"
// priceLabel.text = "\(String(describing: priceSocket.currentTicker)) = \(String(describing: priceSocket.currentPrice))"
}
}