Fetch The Price of Dogecoin On Any Exchange With SwiftUI

Daily Coding Tip 046

The cryptocurrency Dogecoin has had an incredible run this week, fuelled only by hype and celebrity endorsements. Unlike GameStop, where arguments of the company being undervalued can be made, Dogecoin really doesn’t offer any new utility. Maybe that doesn’t matter, but we’re probably going to find out soon enough. Whether you’ve bought into the hype or not, you might be interested to know how to use an API to check the price.

We’re going to start by creating Codable structures for the data we care about.

We’re going to be getting data from the CoinGecko API, which is free and does not require the creation of credentials. I’m bringing back an extension of URL that allows you to set a Published property to decode the JSON response from the API. I’m extending Date too, as I’ll be needing the current time as a string for the interface later.

We’re going to use an EnvironmentObject to store the data that’s shared between our SwiftUI views. When this DataModel class gets created, we try to fetch an image from the web and our ticker data from CoinGecko. There’s an empty string as a Published property called lastRefreshed, and we change this in the refresh function. Now we can refresh the data in the app and be sure that it updated successfully.

We’re going to need a detail view that shows the value for each exchange and each cryptocurrency pair that includes Dogecoin. The TickerData structure that we get from the API has an array of Ticker instances, and all we need to do is access the values there.

We have a refresh button too and this will display our lastRefreshed string from the DataModel.

When we bring these views together we have TickerDetailView. This is a separate page that will be navigated to when the user selects a cryptocurrency pair from the menu. The image I’ve provided is just a Dogecoin logo designed by someone on Reddit, and I thought it would be easier to load the image than request that you add it to your Xcode project beforehand. This spaces the content out, as we’re keeping the amount of data shown on screen to a minimum. We’re using optional binding for the image and the ticker, as it’s possible that neither has been downloaded from the web before the user navigates to this view.

Now we just need to display the main menu, which is simple enough. I’m not sure how the API orders the tickers array, but it’s not alphabetical. I wanted to sort mine as alphabetical, as this would put all cryptocurrency pairs from a given exchange in the same place. After that it’s just a question of displaying a List of NavigationLink buttons that link to TickerDetailView and pass along the DataModel instance as an environmentObject.

This allows the refresh button contained in TickerDetailView to refresh all of the content in the menu, as well as updating itself.

Get more Daily Coding Tips in your inbox!