iOS 15 Async Await JSON Fetching AsncImage Main Actors

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey hello what's up everybody uh welcome back to the let's build that app.com channel i hope you guys are having a good day and i hope you're doing well in the world of a swift development now recently uh ios 15 was just released for public consumption and also what's available now is xcode13 and you can find that through the you know mac osx app store and so today i wanted to go through a very quick tutorial on how to use a new pattern that's now available in xcode 13 and ios 15. and as you can see through the title of the video the pattern is the async await pattern and if we have enough time today we'll also work on async images okay so the goal of today's video is to build out this application here and uh you know it's a very simple app it basically it's going to hit a json endpoint and consume a couple of json objects that we can you know present instead of a vertical list like this again nothing too fancy and it looks like this right here i'm going to hit the refresh it's going to hit the endpoint one more time and fetch the data and once we have it we are rendering our async images here and also you know some string properties on our json object okay so you know that's basically what we are going to work on in today's video and again we're going to be performing all these operations using the new async await pattern hopefully i remember how to do this inside of xcode13 the code is a little bit new to me still but you know hopefully i can present it in a easy to understand manner all right so what do we want to do here is i am going to go ahead and use my xcode project which is right here and i don't exactly want to use this built out project so what i will do is i'm going to create to anyone using command shift n to create a new project here this guy hopefully you guys can see my screen i'm going to use the ios app like this looks a little bit different but you know we should be okay async await pattern and create your project these settings should be fine hit next and just you know save this inside of your computer somewhere and you should be okay hopefully this is going to create with no problem whatsoever i'm on my mac mini m1 right now uh go ahead and change this to the iphone pro max and just slide that guy over i don't really need the documentation panel on the right edge so here is what i have all right i'm going to slide this guy in the back out of the way and i will you know maximize this as large as i can all right so here we go we have our xcode editor again this is xcode 13. it looks uh quite a bit different compared to xcode 12 but you know nonetheless this is what we'll be working in now for the right side preview what you want to do is to you know hit play you can start typing things inside of your code here three now you'll see your changes reflect automatically on the right side and the first thing we will do is to make sure we have a you know navigation view this makes our code look a little bit nicer i'm going to include a scroll view as well and here is my scroll view and that's what we have so i don't care about that text stuff i'm going to go down below here and use navigation title and then we'll say courses like this and again this is what we're trying to now work towards okay so uh next thing we want to look at is to actually fetch our json data and the question is where exactly is our json data going to come from well i'm going to open up a chrome browser and i will paste in my code and just drag it in inside of the screen here hopefully you guys can see exactly what's going on but basically when you hit this end point here let me just maximize this a little larger you'll get this list of json data i'm using a json parser renderer for the chrome browser and that's why it's kind of nicely formatted like so but here is our json endpoint i'll provide this link down below so that you guys can you know use it as you see fit but here is our properties id name link image url and number of lessons the images right here are coming from the image url so you know some of you guys already know how to do some of this using the traditional completion block handlers but today's lesson we're going to be using async await so i'll show you exactly how to do that right now uh first thing you want to do is to create uh some kind of like what they call a view model object and i'll just call this the content view model you want to conform to the observable object now this is a protocol i believe and inside of here just use something like init and fetch data will occur here okay that is looking pretty good and the first thing i want to do is i want to take this content view model right i'm going to go down below and to use this view model you want to observe it using either i believe a state object or an observed object works as well uh we'll just use this in the video so content view model construct a new instance of this guy and the moment that you do that right you can enter whatever properties you want inside of this view model object like is fetching and just set this to false or you know some kind of bullion and you know maybe you want to use a true instead and down below instead of your content view guy you can just monitor your publish variables so if it's fetching and we'll do this right here so this is vm your view model is fetching and we'll just say text is fetching data from internet so you know obviously you can type in whatever you want and i'm going to hit the command option p on my keyboard to resume the preview on the right side okay so here is what we get i will remove that text for now and it is fetching data from internet uh that's happening because the is fetching is uh true so what you can do instead is let's say you set this guy to the false right and instead of here you can do something like dispatch q and async um let's see no main dot async after like this using this deadline and i'll just type out some code and i'll use one second from now hit enter here and let's say itself that is fetching equals to true all right so what that is going to do is it's going to start up our application right here and after one second so deadline now one second from now after that specified amount of time we are going to you know modify these fetching to true if i hit a spacebar right here it's going to refresh so let's hit the resume the is fetching as false at the very beginning and after one second your you know your text string right here is now being rendered out so that's kind of the usefulness of this view model type of object and the other useful aspect of the view model is you can put all of your fetching code inside of you know your review model it doesn't really matter where you put it uh what you can do is you can create a new function and you can say fetch data like so maybe you want to make it private you can do that as well all right next uh we are going to move on to consuming our json data let me see i want to say url string equals the string that we parsed out in the browser and so again this url string is going to be available in the description below make sure you you know copy and paste it and use it otherwise you won't be able to get the data all right so with this url string what do i want to do with it um i want to close out of that guy get some more space here so for the url string right i'm going to use the guard and let url equals this url using the string from the url string right here and uh i'm just going to return you might want to provide yourself with some kind of error message but you know to doors uh today's tutorial it's kind of out of scope to talk about error messages so i'll just leave this for now next thing i will do is i'm going to as a url session like so and you can say shared and this is the interesting part of today's lesson and typically when you are you know fetching data from the internet using url session you might just want to use this data task with the completion handler so you know either one of these maybe this one right here uh this is what you would consider the you know old traditional style of data fetching and inside of ios 15 and xcode 13 you can now use the download data method and i'll show you what this looks like right here so shared and i believe it's one of these methods below so hopefully you guys can see the pop-up right here you'll see data for data from and for this for one takes in a request from this just takes in a url and a optional delegate you see on the right side it says async and it potentially throws you an error um you know there's a lot more to talk about but it's actually really easy to use so i will do that here uh paste in the url and the delegate you can either use no like so or if you don't want to see it just wipe it away all right the next question is uh whenever you you know execute this shared data from url right you can see there's a lot of you know potential errors and problems that can occur and one thing that you have to check is whether or not uh your os is running ios 15 and you can do that using this check right here using this fix like so and you know this is fine but i'd rather just make my application ios 15 targeted uh i guess in other words you want to go through your project settings here and i'm just going to you know target the ios 15 development environment and that should make my error go away so uh once i have that you can see that your ios 15 error is now gone and you can look at the other messages inside of xcode so the first message you want to kind of tackle here is that these async methods they require you to use in a weight like that and that's pretty much just going to wait for the data to come back from the internet and then the next thing you'll do is these functions right here right they can throw an error if let's say you can't reach your url endpoint here so what you want to do is you want to cache this inside of a do catch block like so and we'll catch it and we'll just say print and you know fail to reach and reach and point like that and you can just use the interpolation of the error like so some of you guys might be asking where this error is coming from but basically instead of a do catch like this this is the the implicit error variable that gets caught inside of this duke edge okay the next thing you'll need to do is you are going to have to try the awaiting of your data fetch here as well and once you do that uh the xcode compiler will you know stop compiling about things hopefully and once you do that everything should be okay you'll see uh the last couple of error messages that you're uh kind of shown here is to kind of tackle this async call in a function that does not support concurrency and what this really means is when you're awaiting a an async function like this data guy right here so hit option and click on this guy you'll see the documentation that's async and it throws so in order to in order to call and await function you want to make sure that the the function itself which is such data this guy also needs to be async and once you have that that error will go away and everything should be fine at the moment the last warning this is just a warning is that the data that you get back from this actual call it's actually not being used at all so uh you can do this right here i lead data and i think it's the response of your await is going to be captured inside of this tuple on the left of data and response so you know that's fine and the last thing i will do is i am going to print out the data like so all right the last thing i will have to do is to actually uh invoke this fetch data method call and i need to do that from somewhere inside of my view so that i can you know present it inside of my app and there's a couple of ways of doing this i'm going to remove the private so that it's and then the next thing is to just go inside of here and i believe the uh the view modifier that you want to call is just task right here and it says adds an asynchronous task to perform when this view appears and just click on that and we'll see the vm of fetch data you see it's an async function and it will click on that and everything should be fine uh you'll see that if you click on the fix you'll have the weight here as well let's try to resume this one more time everything is looking pretty good you see the is fetching from data or data from internet and the last thing i want to do is i'm going to run this application inside of the iphone pro max simulator there and what that will do is it's going to invoke the fetch data when the view appears and once that happens it's going to fetch my data from the url string and then at the very bottom we are printing out the data and you'll see the data is uh 2073 bytes and again that's going to represent all of the data right here so there's about 2 2 000 characters is what i assume now the next thing i will do is to just move on to parsing this data into you know some json objects and the easiest way of doing that is to just create a struct and we'll call this the chorus and make it decodable like that hopefully i spell that correctly and then lastly i'm going to use the name as a string and let's just use the id of a string as well and i'm just basically looking at all these properties here so we have the id name and link and let's see i believe this is the link image url and i think that's okay the id looks like a string so the id is a string or the id is a integer rather so what i'll do is i'll specify it as an int and also a number of lessons so you know just standard json decodable properties and once i have that i think i should be good to go all right for the course object i'm going to use it instead of my json decoding right here and again this is pretty easy i am going to use the light courses equals the json decoder and decode it uh using the array of course like so and then we have the data right there all right so not bad not bad now you'll see this warning complaining about the response not being used right so one easy fix to get rid of that is use an underscore like so uh for the json decoder now you have to try the actual decoding otherwise it's not going to work and everything should look kind of fine uh for this right here i'm going to just say print out the courses and i'm going to rerun this with command r it's going to fire this guy up and you'll see all the courses being rendered out here and you know it's just a very long list of data you'll see this async await pattern.course which is my course object and all of my properties are being kind of captured inside of my json object which is this right here all right that's basically how you perform your data fetch and lastly you are going to want to render out this guy inside of your view right so for example the image of the text below uh how do you do that well this is just you know standard swift ui object red ring uh i'll create a variable that's published and call it courses equals the course and let's just you know construct a new array like that uh next i will simply replace this code right here and say self.courses and you don't really need to print the courses so i'll just remove that and let's see next we have inside of our scroll view i'm going to use this i guess i'll use a for each you can use a list if you want but this is what i'll use i'm going to say vm.courses and i will use course in and text and let's see course.name now i don't believe this will work because the uh the course object doesn't conform to this identifiable protocol and let me just kind of fix that now i'm going to simply use a identifiable whenever you conform your objects to identifiable it expects you to have some kind of id property on your object and just you know conveniently for us our json objects contains our id so this is safe to do and then next you are going to want to just uh resume your code i'm just hitting command option p and once you do that you'll see your your data is now kind of being rendered out here this is just simply the the name of my courses right um lastly i guess i am going to uh get rid of this silliness for now and let's see what i want to do here i guess down below right before i fetch my data i'll toggle this guy to true and then once everything is done i will use is fetching equals the false and also if the catch occurs i'll set the fetching is false as well okay that looks pretty good next thing is what i'm going to do here is let's use a progress view instead and i'm going to hit resume and hopefully my code looks okay you'll see that if i hit a space right here you'll see the kind of spinning progress guy for just a brief moment and once my data fetch is done all my objects appear like so okay um that is the very quick lesson on how to set up a json fetching async await function uh which is fetch data here uh there's a lot of kind of a lot of side tangential topics that we can discuss as well for example let's kind of go back to this line of code the wait url session this guy you saw previously we are capturing data and also the response of your you know shared data call from your endpoint up here right uh what can happen is this response object so i'm going to say if let response equals response as um http url response like so and if the status code is i don't know maybe greater or equal to 300 you want to capture that as an error the status code usually in the land of http uh let me just kind of fix this error here so anything above uh 300 it's typically you know not a success and anything between 200 and 299 that's typically a success code so whenever this happens it's usually an error and you can say something like if you know self dot error message equals uh fail to hit endpoint with uh bad status code uh you know that's kind of how you would handle this uh this response error and somewhere up here you might want to use publish var and error message and just set this guy to the empty string and you know you might want to use this inside of your review when an error actually occurs all right so that's one very nice issue to solve uh the last thing you also want to render out in your review are these images instead of swift ui so with the uh the introduction of async image inside of switch ui you can render out these views relatively easily so again there's this async image now available in uh ios 15. and i will use this using the i believe it's the content and placeholder so i'm not a big fan of async image in its current iteration there's a lot of issues rendering out things and maybe i'll show you some of the issues today the url you can construct it i'm going to use this one line of code right above and i'll use the course.imageurl and you can just simply pump this in here uh for the image i'm going to hit enter right here and here's my image that i get back from the url and the next thing i will do is i'm going to say image.resizable like so hopefully i can get this to work so again i'm not a big fan of async image just yet a lot of weird issues with the way async image renders out inside of your view so let's just hope it works for me today okay so as you can see the aspect ratio of my images right they're not exactly perfect just yet um i'm going to go back to my image and use scale to fill once i do that hopefully my image looks perfect um so this looks quite nice one thing that is weird about async image that i can't really figure out just yet i don't know i don't really know if it's a bug or not but if you try to use a lazy v-stack to capture all of your objects in a lazy kind of fashion then the images sometimes they don't render out correctly for me so you see the images look okay and if you're not really looking carefully you might not notice that for this image right here intermediate training core data it should look like this image right here right below the the podcast so for whatever reason if someone knows the solution for why async images aren't being rendered out inside of a lazy v-snack please let me know and you know if you get rid of the lazy and you know render out your entire list again you'll see that your your image actually renders out nicely again not sure why that is but if someone can enlighten me as to what the solution is uh please let me know all right um i think that's most of what i want to talk about for this super long tutorial um if you guys are interested in this refresh button here it's really easy to hook up maybe i'll show that for today's video to wrap up here all right for the refresh button you can go down to your go to your scroll view and down here somewhere it doesn't really matter where you can use the navigation of the trailing button and i'll just call this the refresh button this guy what exactly is it well i'll define it for you right here and let's see what do we want to call this private var refresh button of some view and we will return a button that has the action title and label this guy i'll say vm dot refresh no fetch data and this guy is the uh you can just use the text of refresh like so all right now once you have this go you're going to try to run this inside of the preview or the simulator but you'll see it doesn't exactly once you compile it just yet and the reason is because this is an async function and when you're inside of a button there's nothing really allowing you to run an async method and what you want to do is you know you want to use this async style of code right here so i'll just paste that here and i'll just kind of try to run this i hit this guy right here hit the wait fix and you should be fine i'll talk about this warning in just a little bit but your code should be okay um this guy likes to spin for a long time xcode is getting buggier and buggerier as we kind of progress through the years but you know nonetheless after a while your simulator is up and running you'll see if i hit the refresh right here it should trigger this refresh you'll see it kind of bounces up and down and that looks pretty good um you can also go up here and say vm dot courses dot um removal is the method so i'll just do that so refresh does that and that looks pretty good uh you can also add animation if you wanted to do that and i'll just put that here and here and once you do that you'll see your code looks a little bit strange but you know that's kind of what it does all right um and for this refresh right here you might want to use task init instead uh it's exactly the same thing as this code right here and once you do that this warning should be go away so like that i will run this inside of the simulator sometimes the warnings don't go away from your xcode until you run it inside of the simulator and you know you can hit play or i'm really used to just hitting command r and you'll get your application up and running right here so that looks pretty good every time you hit refresh uh you know you get your data to come up like so um so i think that's pretty much all i wanted to discuss but as you can see as i scroll up you'll see that um all of your data is being fetched asynchronously right you know hence the the name async for your method and every time you fetch things asynchronously what that really means is that you're doing you know operations on the background thread and you know that's really useful so that your applications can remain uh functional and the user can you know swipe up and down but one thing that you have to worry about is that you want to make sure that your methods get back onto the main ui thread so i believe the traditional way of doing this is using the main and async right here get back on the main thread and um you know this actually modifies the ui so that's kind of why it complains and you can try to run your code inside of the simulator but it says that it can't really convert this code to use this dispatch queue thing so what i would like to do instead is i'll replace this code and i'll just fix this using the i believe it's the main actor like this i can't remember exactly the syntax for this guy but i believe that's it we have our main actor here and now that you run your code inside of the simulator right it's no longer complaining about this being uh being worked on on instead of a background thread so this is pretty much the fix for that bit of code uh the topic of actors is you know quite vast in terms of understanding how async await works so i'll you know maybe talk about actors in a later video but hopefully you found today's lesson helpful if you haven't if you guys have any questions about async and weight please let me know i'll provide this url for the endpoint down in the description as well as this entire project i'll zip it up and put a link down below as well if you guys liked today's video make sure to hit the thumbs up and you know always consider subscribing to the channel uh if you guys have any ideas for future topics please let me know as well and i'll see you guys later bye
Info
Channel: Lets Build That App
Views: 7,341
Rating: undefined out of 5
Keywords: ios, swift, development, tutorial, learn, xcode, programming, code
Id: bxCDL3kY8XA
Channel Id: undefined
Length: 31min 28sec (1888 seconds)
Published: Thu Sep 23 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.