Creating a Coin Model based on JSON response from an API | SwiftUI Crypto App #3

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] all right what's up everyone i'm nick this is swiffle thinking where we cover all things swift and swift ui related and in this video we're going to create our first model it's going to be called a coin model and it's basically representative of the coin data that we're going to be downloading from the internet we're adding it this early in the course because we're going to use this coin model on so many different views and move it around our entire app so it's important to just get this out of the way early on in the course and there actually is a little bit of kind of boring code in this video where we have to type out certain things very manually and because of that i've actually included some of the files that we're going to be creating in the resources folder that i have on my website and i will link it below so if you want to just follow along and not actually type everything definitely just check out their resources but if you do that i do not recommend just copying and then skipping this video because there is a lot of good information here that you will probably want to know if you're going to do this on your own and in your own apps all right welcome back everyone i am back in our xcode project and in this video we're going to start setting up the model for the data that we're going to download and put onto the screen here for all of our coin prices so what we're going to do in the navigation view here outside of this core folder i'm going to right click create another new group and this is going to be called models this is where we're going to put all of our models in our app i'm going to bring this actually below the extensions here and the first model we're going to create let's right click the folder create a new file this is going to be a swift file and we're and again we're using swift instead of swift ui here because we don't need the preview we basically only use swift ui when we're needing the preview to make a view but now we're just going to create a model so it'll be a swift file and i'm going to call this coin model go ahead and click create and inside here let's create a class let's call it coin model and let's open the brackets i do want to point out here that i'm calling this coin model to just be very specific that this is a model because this is a tutorial on youtube but if i was actually making this in a production app i would probably just call this coin and not use the word model but for our purposes this is just being extra explicit so you guys know exactly what's going on here and now we're going to take a quick first look at the api that we are using so i'm going to go to coingecko.com and this is basically just a public website that has cryptocurrency data that we can see here but really useful they have underneath the resources they have a crypto api and if this api ever does go down which i've been using it for several years now i've never had a problem but if it ever goes down i will put in the comments below a replacement api that you guys can use but while we're here just to show you guys this is it is a 100 free api we don't need any special keys it is reliable at least they say it's reliable and they have over 7000 coins 400 exchanges pretty much all the data that we're going to need for our app i'm going to click get started here and the cool thing about this api is that they have this web portal which is super beginner friendly so if i start maybe here with just like the the ping just check that the api is online we could click try it out and we can click execute and this actually gives us this is the url we need to request in our code and this is the data that we're going to get back if it's successful so all we need to do is add this into our code request it and then we're going to get this json data back that says gecko says i guess it says v3 to the moon we're not going to actually use this url but you can see how this is so beginner friendly and super helpful when dealing with apis because sometimes when you're using these third-party apis they don't have any documentation and it's kind of hard to figure out what url you really need or what the download is going to look like so this is super handy i'm going to click cancel here close up the ping and the first one we're gonna actually use is the markets api down here so i'm gonna click on this markets and i'm gonna click try it out and there's actually a bunch of settings that we could set when we are requesting this url first we can set what currency we want so i'm going to use usd but obviously you can change your currency by just typing that in right here and then we can give it specific coin ids if we want certain coins only but we're going to leave that blank so we're just going to get the top coins we can also set a category if we want maybe like decentralized finance coins or stable coins we're going to leave that blank as well we want our query to order by market cap descending this just basically means that the first coin is going to have the highest market cap and the last coin we get is going to have the lowest market cap then we can change how many results we want so if we only want to get the top one or we want the top 10 we can set this to 10 but we're going to actually just get the top 250 which is the most that it lets us get per query so here i'll put 250 and then we can add a page here so this is super useful if we wanted if we want to perform multiple queries so if we keep this as one it's going to get the top 250 coins if i put this as 2 it's going to get coins 250 to 500 because that would be page 2 of this request so if you wanted to keep downloading more and more coins you could basically call the same api and just increment your page number so three four five whatever you want but we're just gonna get the first page so the top 250 coins and then we have this option to include a sparkline so this is extra data that we can get and the sparkline is just basically the prices for the last seven days so if we don't need them we'll click it to false but we are gonna actually use these so i'm gonna set this equal to true we're gonna use the last seven days data to make a chart of that data later on in the course and then finally if we want to get the price change percentage over the last maybe hour 24 hours seven days we can add that here and we're going to get the price change for the last 24 hours now we can click execute and i just love how simple this is and easy to use and down here first we can look at our request url so this is the url we need to request in our app and just looking at this url we can see all the settings that we put we have the currency is usd the order order is market cap descending the per page is 250 coins we want page one and then sparkline is true the price change is 24 hours so if we wanted to then get page two all we need to do is set is request the same url but page we can change to number two so before we move forward i'm just going to copy this url because we're going to use it i think in the next video but i don't want to lose it so let's copy this url here and let's i'm going to put a multi-line comment and at the top let's just call this coin gecko api info and then in here i'm going to first add the url to paste that in and the reason i'm making this multi-line comment is because up here later we can command option left arrow and fold it up and again that's also the editor code folding fold you can fold it up so it's nice and neat but while we have this open let's also copy and paste some of the data that we're returning so i look back when we request this url it's going to return this data and this is actually a very long web page now because this is a ton of data that we are getting you guys can scroll down this for a while but essentially if we look at it it's going to give us an array of this json data and the data obviously the first item here is bitcoin symbol is btc we get the name we have a we have a url to download the image for the icon name for the bitcoin and we get all this other lovely data which we can use in our app and it's so awesome that this is free so i'm gonna copy this from the opening from the opening brackets here i'm gonna scroll down to the bottom so let's see right it's this bracket here right after the price change i'm holding the shift button and i'm gonna click right after the price change here to the closing brackets i'm gonna copy it and i'm going to go back into our code i'm just going to paste this here and let's call this json response i'm going to paste the json response that we get so this is all the data that we are getting back from json and i'm just going to delete some of this sparkline in 7d because we don't need all this in the comments so i'm just going to delete most of these rows we're going to use them in the actual app but we don't need it in this comment here so this is all the data we're getting back which is a lot of data and we can go ahead and start creating our coin model directly based off of this so we have an id that's a string we have a symbol that's a string so we can start doing let id of type string let symbol of type string and we can go through the rest of these and type these all out and it would probably work but that actually is a little bit challenging you know you might get wrong if you mistype it this is a lot to just copy and paste directly so what i recommend and what i do when i'm building out these apps is i take that json data and i go into a website called app.quicktype.io there's a couple websites like this out there and then in this app i can just copy and paste our json data and when i do that i can set the language to swift and will automatically give me a it will automatically give me a model for what we're looking for so i can see that down here so we're going to actually use this plane types only here just to get the core values and i actually went ahead and looked at the data and made this ahead of time and i noticed that sometimes some of the data is not valid for every single coin like maybe like the circulating supply isn't available for a specific coin so because of that we're going to make all properties optional and that basically gives us these question marks at the end of all of these so i'm then going to copy this code which we can just click copy code here on the right side and jump back into xcode paste it down here let's delete this comment and delete the import foundation and this struct is going to be called coin model so to delete our original coin model and a couple things i want to do to edit this really quickly first off the id the symbol and the name i want to make sure that we do get them so i don't want them to be optional so i'm going to delete this the image i also want to make sure we get which can't be optional then the current price i want to make sure we get so i'm going to make that its own line we'll say let current price and that will be of type double i'm going to get rid of the current price down here and while we're on this double i notice that the values actually come through as doubles not as integers and this app i guess just thought these were integers because they were rounded in that example but really but to be safe let's make all of these doubles so i'm just going to make this a double make this a double make this a double make this a double and then finally we have this roi which is of type ns null i guess because in our example it didn't have an roi so i'm just going to actually delete this because we don't need that we're not going to actually use it so now we have our coin model and i should have mentioned earlier that i'm actually going to put this coin model file into that resources folder so if you download that resources folder from my website which i'll also link in the comments of this video you can just download this and you don't need to go through all those steps although understanding how to get to this spot is really important in making an app because you're always going to have to set up your models and this is a very complex one i'm going to delete this comment here all right now we're going to take our coin model we're going to make it conform to identifiable and we're going to make it conform to identifiable and because it has an id it already conforms to identifiable so we don't actually need to do anything else and the reason we're doing this is so that each coin has an id and this way we can use it in those for each statements in our view and then we're gonna also make it conform to codable we're gonna get an error message that does not conform to decodable and that's because there's one type in here that is sparkline in 70. and this sparkline which is also down here it's a subtype does not conform decodable so down here we can also add codable our error should go away and then lastly i want to add one more variable to this coin model and we're going to say down here let current holdings that'll be of type double and we'll make it optional as well and this current holdings is going to be how many how many coins the current user is holding so this was bitcoin and i had one bitcoin the current holdings would be one but of course we're not downloading that from the internet that's why we're making optional because this will always fail when we initialize it and we'll start at zero and then we're going to update it so we can update the current holdings afterward and one final thing we need to look at here is that when we decode using the default codable it's going to look for the exact names of all these variables so the current price with the camel case here but if we look at the actual data that comes through uh the current price has an underscore and there's no camel case so we actually need to decode to this current price string here because of that we need to add our custom coding keys to this coin model so down here i'm going to add a enum we'll call it coding keys and this will conform to string and coding key open the brackets and in here we basically need to add coding keys for all of these and this is one of the least fun parts of coding when we have to actually do this so i've put this file again in the resources folder so you don't actually have to type this out but if you want to type it out with me we basically need a coding key for all of these so what i'm going to do is click the plus sign here add an editor on the right and in this editor on the right i'm going to scroll up to our json data and then on the left here we can start adding coding keys so the case and we need a case for all of the variables here if the name of the variable is exactly the same as the json title here as the json key here then we don't need to give it an extra string so for this id for the symbol we can just keep it as the regular default so here we'll say case id comma symbol comma name comma image and that's because these four all have the exact uh image is the exact same as image in the return json now but the current price here has different text now we're going to do current price we'll say case current price and we need to give this an explicit string so i'm going to just copy the current price from here so i'm going to set it equal to the current price like that i'm going to do this for all the rest of these as well so now let's do market cap case market cap equals market cap i'm doing a lot of copying and pasting instead of typing out because i don't want to get these wrong case market cap equals market cap rank let's do fully dilution fully diluted case this equals this and i know this is dreadful it's a dreadful for me too but this is uh what we have to do here case high 24 hours equals high 24 hours case low 24 hours equals i'm gonna put a little bit of music over this part so that it is not just me sitting here typing and talking to [Music] myself [Music] and then finally we'll do just current holdings which we know will fail that's not part of the json data if you did this correctly and you have and you have a coding key for all of the variables that error should now go away if you're missing one then this will you'll still have an error up here and when we actually go to download data if you are missing any of these specific pieces of data you can always just come back and and fix exactly what you're looking for now that we have our model i want to add a little bit of logic uh so that we can actually use this coin model in our app and the first thing i want to do is add a function so that after we get the model we can update the current holdings so underneath this enum here i'm going to create a func we'll say update holdings and we'll open close parenthesis and this is going to return us an updated coin model which is actually going to be a new coin model we'll open the brackets and when we call update holdings we're going to pass in an amount which will be of type double this will be how many holdings that we now have and in here we're just going to return a coin model and we're going to open the parentheses and we have our two completions here the the first one is an initializer from the decoder and that's if we had json data and we wanted to create a coin model but now we also have our second decoder where we can actually input all of the data ourselves so we're going to do this second one here and it looks ugly but these are all of the values that we just added up here right so all of these so when we create a coin model it's going to ask us what all these values are and when we're in this function we're creating a coin model here and we're calling this function here from within a coin model right because this function is actually inside an existing coin model so therefore we can reference all of the values that are already existing in that coin model and that's what we're going to do here so in this updated holdings we're going to reference the id at the top there we're going to reference the id and this is the id that is at the top there that's already in this current coin model we're going to do the same thing for all these values we're going to add the symbol the name the image the current price the market cap market cap rank i'm literally just copying the exact names of the parameter fully diluted value valuation total volume high 24 hour low 24 hour price change 24 hour price change percentage 24 hour market cap change 24 hour market cap change percentage we have the circulating supply we have the circulating supply the total supply the max supply the ath the ath change percentage the ath date the atl the atl change percentage the atl the date we have the last updated the sparkline in 70 the price change percentage 24 hour in currency and then finally we have our current holdings and this is what we want to update and we're going to just update this with the amount that we're passing into the function so paste that right here and this will be the amount so when we call update holdings it's going to give us a new coin model with all of the same data as the current coin model but with the updated holdings all right i know it was a lot of code just to get to that but this is going to come in handy when we start updating our own portfolios there's a couple more things i want to add into this coin model here i'm going to create a var called current holdings value that will be of type double open the brackets and i want this to be the value of our holdings so scrolling back up so if i had current so if this coin model was say bitcoin and my current holdings was one the value of that would be the current holdings times the price so we have the current price here so if i was holding two it would be two times the current price and that's the logic that we're going to add in this so going down here we're going to return so here say the current holdings and the current holdings is an optional double so optional w up here so if we don't have any current holdings if it is nil we'll just set it equal to zero let's put that in parentheses and then we want to multiply the current holdings times the current price and just like that we can now access our current holdings value and lastly i want to also get the rank so we'll say var rank of type int and we'll open the brackets and here we're going to return the market cap rank and the market cap rank is coming through as a double so we want to convert it to an int by just calling int open the parentheses and i think this is also optional we'll get an error yeah it's optional so if we don't have a market cap rank we'll just make it zero so now we have our current holdings value as well as our rank all right so i'm going to zoom out here and scroll up a little bit and because we have this comment we don't actually need it but i like to keep the comment here in case like another developer is looking at our code or if like we type something wrong we can reference the json data here without going back into coin get go so to leave the comment here but let's fold up the comment so that it's nice and neat and that's it for this video so i know this was a stressful video this is definitely the most boring video in this series sorry that i had to put you guys through it so early in this course but now that we have our coin model set up we can start actually downloading coins and putting them in our app and it's going to be awesome and we're going to use this throughout pretty much our entire app which is why we had to set it up so early in this course alright guys thank you for watching as always i'm nick this is swiffle thinking and i'll see you in the next video you
Info
Channel: Swiftful Thinking
Views: 3,508
Rating: undefined out of 5
Keywords: SwiftUI Codable, SwiftUI decodable, SwiftUI encodable, SwiftUI API, SwiftUI how to use api, SwiftUI decode from API, SwiftUI JSON data, SwiftUI JSON, SwiftUI decode JSON, SwiftUI codable JSON, SwiftUI JSON api, Decoding data from API SwiftUI, Decoding JSON SwiftUI, how to decode JSON SwiftUI, SwiftUI how to decode JSON, SwiftUI create Model, SwiftUI create model with JSON data, JSON data model SwiftUI, SwiftUI JSON data model, SwiftUI coding keys
Id: UaPAis0vtK0
Channel Id: undefined
Length: 24min 48sec (1488 seconds)
Published: Thu May 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.