Parse JSON in App Like a PRO (Xcode 12, Swift 5, 2020) - iOS Development

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what is going on you guys welcome back to another swift video in today's video we're going to take a look at parsing json but more specifically parsing json from a file that's locally contained in your app so here we've got a json file with a couple bits of data different sections and whatnot and here we've got an app which can actually take that data parse it and then render an appropriate table view from it and you can even notice that you know the data is sectioned off we've got our section titles in the header and all that good stuff so we'll take a look at how to do this honestly why you should do it because it is pretty useful as well as how to handle errors properly so that said make sure you destroy the like button as always and that like button really helps hit subscribe while you're at it if you're a returning viewer i'm gonna go ahead and be annoying and wait for you guys to hit like should play the jeopardy song at this point but now we'll uh we'll open up xcode and dig into it get excited we'll talk about some json let's do it quick pause before we get into the video if you haven't seen it already i am hard at work putting together ios academy dot io a community where all of us ios engineers can come together learn how to build some of the top apps like facebook youtube and instagram in addition to interview prep to land some of these ios roles at top tech companies so if you're interested in the free and premium content to come head on over to ios academy dot io and enter your email address in the waitlist form and you will be notified as content becomes available that said let's get into the video alrighty so let's get started by opening up xcode and we're going to jump right in and create a new project we're gonna stick with the app template and let's go ahead and call this uh file parsing json go ahead and create it and save it and before we get into the weeds of the code let's pick a simulator from this list we'll go with the 11 pro max since i've got it loaded up already hit that run button to get it running just like that and we're going to be doing all of our work in the view controller so let's jump into here let me also expand to this side to give ourselves a little more room to work and let's talk about json parsing so before we can actually parse json and show it in our table we kind of need json so i'm going to go ahead and create a json file with terminal so go ahead and open up terminal and cd into your project folder that you just created i put it on my desktop and in here we're simply going to create a json file called data.json touch just creates a new file so go ahead and do that and once you've done that you can actually close terminal and right click on this project folder and there should be add files right there and if you open that you'll see that that data json is somewhere in here there it is so go ahead and add data.json directly into your project like that and in here let's go ahead and add some json so json of course is a store of key value pairs and we are going to have an array of arrays so i'm going to go ahead and say our json which starts with the curlies has this one array in it and then every uh next rather every element instead of being an array of arrays it's every element is going to have a title we'll just say like fruits for now as well as items and this is going to be an array of strings so let me go ahead and say apple i won't add too many for the sake of time but orange grapes and i don't know let's do strawberry so let's just go ahead and copy and paste this since we're going to be lazy like that so we're going to copy this whole uh block right here put a comma paste and just do that one more time let's quickly change up these values so first one we'll do cars we'll do bmws mercedes hondas and i don't know ikea and then the third section we'll do states so we'll do new york florida california and idaho so cool now that we have some json data in here we need to actually get to the meat of this video which is how do we parse this and then use it in our app so once again going over the structure of this this is a collection rather this is a json object with one array in it and each of these arrays each this array each of the elements in it is an object with a string for one of the keys and a array for the other so let's go to our view controller and the first thing we're going to go ahead and do is call a function called parse json and we're going to create that function of course down here called parse it's a private function called parse json and we first need to get a path to this file that we've brought into our project so we're going to say guard let path is bundle.main which is the current application bundle think of it as a folder and we want to get the path for a resource with a type so the resources of file name and type is the file extension and i believe this returns optional we'll see in just a second yep it returns optional which is why we i added the guard let uh now from this we're going to get a url to the file so we're going to say a url is a url and we want to get a file you want with the file url with a path and pass in the path just like that and let's see what else do we want to do now we want to take this url and create data out of it so we're going to say let json data is going to be data and we want to pass into data a url so i believe it's contents of url let's just go through this list yep contents of url and looks like this function throws we're going to pass in the url here but because this function said throw what we want to do is put this in a do catch and put a try in front of this and if it's you know if it fails to get the data we're going to come into here and we'll just print out whatever error occurs just like that and now that we have the json data this is no different than if you got the json data from an api call you can go ahead and parse this data with codable so we want to create a model that represents basically whatever the structure of our json here is so once again it's an array of these objects so we're going to create a model down here called let's call it uh this is called a result for the sake of simplicity and looks like result is going to have an array on here and we'll just say this is data and this basically is a collection of result item and the result item and mind you i'm just making up these names they don't actually map to our json but now in result item each of these has a title and the items property key so we're going to say we have title which is a string and then we have items which is an array of strings whoops which is an array of strings so we're going to try to parse the json into a result which is a you know a a dictionary with the root element as a array we actually might able might be able to simplify this a little more by just dropping these end curlys but let's see if this actually works and then we'll modify as we go along so we're going to say v we can actually put we can leave that there we can create a var result here which is of type results and we can say result is try json decoder and we're going to try to parse our result model which is the struct we just created from the json data and i believe this isn't optional json data so it shouldn't give us an error okay cool and this is result it's it's complaining that we might not use it and then down below what we'll what we'll do here is we'll say if let's result equals results uh let's print out let's print out the whole result which isn't really that useful but we'll see in a second let's put a return statement here and let's print that in this case failed to parse so go ahead and hit command r and let's see what we get down here in our console it looks like we get an error so data is corrupted uh it's complaining basically that the given data was not a valid json so that means i made a typo in our json file so let's see we have a dictionary here these are all dictionaries this is pointing to an array we've got our commas here um let's see let's get rid of these and uh let's get rid of these and curly braces so but the root of this is now an array and it contains a uh dictionary i guess we actually need a root key so let me actually go ahead and undo that and we'll say that this array has a key of data and data points to this i just did a control i which fixes up our alignment i believe this is proper format i guess we'll find out in a second let's come back to our model and i think we already called the data which we did to go ahead and run that one more time and let's see if it complains again and if it does we'll debug it together all right cool so no complaint that time but we got our result printed out so we've got our title in here cars and we've got our items and now that we have our data what we can actually do is we can use this data and these models to drive our table view which we're going to set up in just a second so i'm going to create a new swift file here just to organize things a little bit we're just going to go ahead and call models and i'm just going to copy and paste those models that we created in here and let's jump back to our view controller and just to go over this code one more time real quick basically what we're going ahead and doing here is first we're getting a path to our file which is data.json then we're converting it to a url and then subsequently data and then we're trying to parse that data into our result here so what we can actually do is let's go ahead and create this result as a global property on our controller just like that we're going to assign the result to it and none of this print statement nonsense anymore since we know it's working now and let's set up a pretty basic table view so this sets up our results model here and we're going to create a basic table view and we basically have gotten through the parsing bit of it but i think it's important to see the actual point of why why the heck would you want to parse it and you know the answer is really to present it onto your controller we'll say the frame is zero to star and the style is grouped we're going to return the table and we want to make sure we register a table view cell for a given id we want to make sure we add it as a sub view just like that we're going to assign the delegate and the data source just like that and it's going to start complaining because we haven't conformed to those protocols so we're going to add two conformances up here for the ui table view delegate and ui table view data source and also if you're not familiar with table views i've got so many videos on it definitely take a look there uh that'll be much more help than me just kind of running through this super fast right now let's put json there we're going to have some table view functions and we're going to have number of sections will be return results dot let's see result has a data array and we're going to return result.data.count if it's nil we'll return zero next we are going to return number of rows by default it's zero we're going to say if let results equals results we're going to return result.data section dot items.count and then lastly uh cell for row at index path we're going to dequeue a cell with table of view dq reusable cell with a given id and an index path we're going to return the cell and then in between here we want to update the cells text labels text and first we want to get the model so we're going to say the model is going to be results dot data and then the index path dot section from that we're going to get the items and from that we're going to say give me the given row and from that i think that should point to text now this might be optional but you can assign optional to this text property so that actually should not be an issue if you go ahead and hit command b let's make sure everything is compiling which it is and actually one thing we forgot to do is let's actually implement one more function called title 4 section because we do have a title property in our uh in our json so here we can return results.data section dot title and if it's uh nil we'll go ahead and simply return nil because this function can take string optional as its return value so go ahead and hit run and now you can see we've basically taken that data and we've cleanly parsed it out into models that can be used to actually do something useful in our app and in this case that useful bit is rendering out a table view so once again just to revisit since i went through that fairly quickly before we look at the table view stuff the json stuff is really a matter of get the file right get it as a url convert it to data because at the end of the day json is it can be represented in data after that try to parse it into our results and our results is basically a model that we put together which basically mirrors how our data looks with the keys and the given value types make sure they conform to codable since that's kind of the underpinning of json parsing and as far as the table goes you know all we do here is we create a table with this anonymous closure fashion if you're not familiar with this i've got a video on this as well we make sure we set up the parsed model before we actually you know set up the table view and in the table view we basically take that results model that the json kind of gets parsed into and we use that to really back our table and render it so you can see all the stuff here and that's basically all there is to it in terms of parsing json from a file or even like you know from an api call so the last thing i'll mention here which is pretty useful is what i like to do is when you're working on an app and you might not have the api hooked up if you have an api or you might be you know there might be rate limits to whatever api you're working with it's really helpful to have mock data as a part of your app just so you can go ahead and play around with uh you know basically debug your app as you're building it without getting live data and this is a pretty common use case uh you know in a lot of places you can imagine even like working at like facebook or instagram their whole app is pretty based on the data that comes back from the api so mocking data in this really simple way with a json file is super powerful highly encourage it very useful to get your apps off the ground so that said if you haven't destroyed the like button already make sure to do so for the youtube algorithm comment down below any suggestions questions do you find this useful do you parse json in a different way leave anything down below comments also definitely help the youtube algorithm stuff i also love hearing from all of you guys of course hit subscribe if you haven't done so already and enjoy the daily uploads thanks for watching i'll catch you guys you
Info
Channel: iOS Academy
Views: 17,271
Rating: undefined out of 5
Keywords: swift 5 tutorial, swift 2020, swift, swift 5, swift tutorial, swift for beginners, swiftUI 2020, swift programming, swift basics, swift apps, make iPhone app, swift make first app, swift json, swift coddle, parse json in swift, parse json swift 5, swiftUI parse json, swift 5 coddle, swift 5 parse json from file, json parsing swift, parsing JSON swift 2020, parse json tableview, swift json to codable, swift json models, swift array codable, parse json for beginners swift
Id: g0kOJk4hTnY
Channel Id: undefined
Length: 18min 17sec (1097 seconds)
Published: Wed Oct 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.