SwiftUI Bitcoin Price Ticker Using WebSockets

To get real-time cryptocurrency updates, I’ve generated an API key and used the WebSocket URL from this website.

A screengrab from Finnhub

The following SwiftUI view consists of an image that holds an SF Symbol with a foreground color set along with a text that shows the real-time price updates:

The priceResult needs to be published from the ObservableObject class — WebSocketService.swift as we shall see next:

In the above code, we’ve defined a few properties and set up a subscription in the init method. You need to replace XYZ with your own generated API key.

The operators used on the Publisher are important. Debounce is used to slow down the real-time updates and removeDuplicates is used to send only those updates that are different from the previous value.

To manually publish the changes to the SwiftUI view, didChange.send() is triggered when the priceResult property is updated by the Combine subscription.

The remaining part of the WebSocketService class that constructs the WebSocket URLSession is given below:

The following struct models are used for decoding the API response:

I arrived at the following result when the application was built on a watchOS simulator: