SwiftUI MVVM Pattern (Model View ViewModel) - Xcode 12, 2021, Weather App, iOS Development

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what is going on guys welcome back to another swift video in today's video we're going to do a deep dive into mvvm pattern in swift ui and specifically we'll take a look at a real world example with this weather app where we open it up we go and get some data and then boom we get the data and the view is fully reactive and updates you know on its own as it should so we'll take a look at how to put this together the kind of good boundary and architectural lines of models view models and views and all that goodness so if you're into that if that sounds good to you make sure you start by destroying the like button down below for the youtube algorithm if you're new to the channel and like ios and swift consider hitting subscribe to stick around for daily content that all said and out of the way get x good ready get excited let's build out this weather app with mvvm at its core quick pause before the video this video is brought to you by ios academy dot io if you're interested in building some of the top apps from around the world like youtube instagram uber and facebook head on over to ios academy dot io and toss in your email in the waitlist form here to be notified as content becomes available content includes interview prep free courses premium content how to build tick tock messenger instagram and anything else you could think of in between that said let's get into the video all right we're going to get started by opening up xcode and creating a new project here we're going to stick with the app template under ios and i'm going to go ahead and call this project mvvm weather make sure your language is swift and both lifecycle and interface here are set to swift ui go ahead and continue save it wherever you'd like and the first thing we're going to do is expand our xcode window hit resume to get our preview loading here and once this guy is loaded up we'll get straight away into it so mvvm is the concept of architecting your app in three primary components of models view models and then the view itself so we already have this content view thing here so let's go ahead and create two more swift files by right clicking and hitting new file and the first one here i am going to call models so there is the m and then let's go ahead and create another file and it will be a swift file and we'll go ahead and call this view model so pretty simple i've also got a page opened up here my browser which is an api returning some json it's using the free api for open weather map we're going to be doing a real world example of building out a basic basic weather app with this api and the whole idea of mvvm is you know as the data changes for the view model from the model it should automatically update the ui right we shouldn't have to go and manually do that so the model represents basically the actual route data so i'm going to say this is data and the view model once we create it will represent basically the data needed by the view now in swift ui there is something called state object which we can go ahead and mark a instance of a viewmodel and whenever something in that viewmodel changes the contents view will know to update the related ui elements so first let's go and create a view model here now it's going to be a basic class and i'm simply going to call it weather view model and it needs to inherit from observable object just like that and basically we're going to have four things in here that we are going to use to update our ui and that is going to be a title which is a string and it's going to be empty by default i'm going to copy and paste this three more times the next one will be description text then we're going to have temp for temperature and we'll also go ahead and have a time zone on here now what we also need to do is mark each of these properties as at uh published whoops that's not what we want we want at published and basically what this is saying is every time that these properties go ahead and get updated any view holding on to an instance of this view model will go ahead and update the respective ui so here is our contents view so i'm going to go ahead and create an instance of this we'll say view model equals an instance of our weatherview model and we need to go ahead and prefix this as a state object just like that now before we actually go ahead and set up the api call and our model structs let's build out a very basic user interface that's going to auto update itself now let's see what this preview is yelling at us about because it's not wanting to compile there it goes just being typical xcode i'm going to change this to be dark mode here and let's go ahead and build out a super simple ui now obviously this whole concept and architecture scales quite a bit so you can build out whatever you want with this approach but i'm just going to have a navigation view here with a vertical stack i'm going to give it a title of let's say uh weather and vvm and then in here we're just going to have four text labels and the first one instead of actually giving a text directly we're going to get out of the view model the particular thing we want to show so our first is going to be title and let me just copy and paste it then we'll say basically description text we'll have the temperature and then the time zone as well let me actually put the temperature at the top right next to the time zone so it looks a little better and let's see let's go ahead and also give each of these a nice larger font size so i'm going to say the temperature or the time zone let's say it's 32 temperature is probably the largest one we'll say 44 and both of these guys will be 24 respectively like that so it looks pretty great we don't see anything in our preview because we don't actually have any uh data there if we wanted to see something maybe instead of making these an empty string we'll make it a dash by default that way if we go back to our content view and give this a resume one more time let's give it a sec to build and update the preview here sit try again we should start seeing four dashes in there just like that so cool let's go ahead and set up our api call so once again i've just got a url to show the current weather in new york we are going to make an api call so we're going to make this api call whatever we instantiate our view model which is basically whenever the view loads so i'm going to override the init and we're going to say fetch weather now this is going to have a function to fetch weather and what we're going to do is create an api call i've got a separate video actually several separate videos on how to do a basic api calls if you're not familiar with this stuff i mean feel free to follow along but those videos might uh be useful to watch next so we're going to create an api call with a url and a completion handler the completion handle handler will return data a response which we don't care about and an error if anything goes wrong and at the end here we're going to say task.resume now we also need to create that url so we're going to create it right up here with the string that i copied from my browser and we're going to say else return if we fail to create that url for any reason and let's see we've got our task we're starting it up with the resume call in the closure we're going to make sure we get data back and we're also going to validate that an error didn't occur hence saying error is nil and now that we have data back we need to convert the data to our model now we only have a view model at the moment which is just these four properties we don't actually have a model um what we need to do is create them so we're going to go into our models file and i'm just separating them in files just for the sake of organization but we want models that are going to mirror the json here so i'm going to keep it pretty brief which is why we're only doing four different properties there but i am going to call this weather model it'll be codable encodable is the protocol we can use to convert json data directly into structs and the first thing we're going to want is this time zone thing in here so i'm going to bring that in and just paste it in it needs to match identically with the type to work uh the next thing we're gonna want is the current weather which looks to be another object so i'm gonna say current is current weather now this is gonna be another sub model so we're going to create it there just like that and in this model i think there's something called temp which is a float for the temperature which is somewhere in here right here right right about there and then we also want to get the title and description which is in this sub array of weather and it has a main and description in it so um i'm going to go ahead and create that here we'll say weather is an array of weather it's called a weather info now these names were destruct you can go ahead and kind of make them up as you see fit they don't need to match anything but in here we're going to have a main which was a string and a description which is also a string and just to recall here i'm getting those keys directly from the json so there are the three models we are going to need and now what we can do is back in our view model where we do the api call now that we have the data what we can do is we can try to convert the data which is bytes to our model so i'm going to say model is json rather try json decoder and we're going to try to decode our model from the data so let's see that's not what we want we want json decoder decode our model from the data and if something goes wrong we'll just go ahead and print out failed now that we've got the model it's pretty darn simple actually what we want to do is we're just going to get out of the model these four properties and update their values and the beauty of mvvm and swift is because this is being observed as a state object here in our view as soon as we update those published properties our ui will update automatically and we'll see that in just a moment so now what we want to do is we want to update those publish properties now we need to do that on the main thread since it's a requirement and also because it will drive ui updates so let's go and update these one by one so we'll say self dot self dot title and our title is going to be our model dot weather oops model dot current dot weather dot first dot main and this might be nil so i'm gonna go ahead and say the default value is no title the description is basically identical i'm going to say no description and instead of main it's going to be description and we're going to assign this to description text and let's see we also have a temperature so i'm going to go ahead and here we are going to say the temp uh is our model dot current.temperature now temperature is a float so i'm just going to interpolate it here into a string you can hit i believe it is option shift eight to get the degrees symbol like that and the final one is self dot time zone so we'll get time zone make sure you add it without the dollar sign otherwise you'll hit errors and this is going to be assigned to model dot time zone pretty simple so go ahead and hit command v everything should be compiling let's go back to our content view and i suspect we can actually run this in the preview here so right now when our app is you know idle we have nothing but as soon as i hit this live preview it'll go ahead and kick off that api call and boom there is our data so um if we actually go and refresh this page to get the latest data you'll see that it is new york the temperature should match 24.8 so no funny business going on here we could in fact just change the longitude and latitude and get different data but what's really great about this is you don't need to check you know once the data comes back update the ui it's all fully reactive uh which is kind of the point of mvvm so that's basically it let's do a quick recap so in our view we have our view created pretty simply we have our view model set up here and it is being observed because it's a state object now one thing i'll highlight here is some folks might hold this as an observed object and it is similar but slightly different in the way that swift ui manages the view most of the time you're going to want to stick with a state object i'm not going to go too deep into that next step we have our models that we are getting rather creating from our api call which is pretty basic swift not kind of swift ui specific now in our view model we have a class which is inheriting from observable object this has to be a class and not a struct and in it we have our four properties that are showing things in our ui that are driving the ui and all of them are marked published as soon as we create the view model we go ahead and make an api call to this endpoint and once we get the data back we go ahead and just update those properties and since they're marked published swift ui looks at them and so these swift ui is like okay we need to go ahead and update the view boom view update happens and you're good to go so that's it so if you've enjoyed the video if you found it useful if you just enjoyed watching it definitely leave a like down below helps out the video the youtube algorithm the whole nine yards comment if you have any questions what do you think about swift ui what do you think about this pattern i think it's pretty great it's pretty simple to wrap your head around and of course if you haven't done so already hit subscribe to join our community and channel and grow uh this entire thing together and also helps me make more video for all you guys so thanks for watching i'll see you guys in the next one
Info
Channel: iOS Academy
Views: 6,982
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, swiftUI mmv, swiftui, swift pattern, swiftUI basics, swiftui mvvm tutorial, mvvm swiftui, mvvm swiftui 2021, 2021 swiftui, 2021 swiftUI mvvm video, mvvm swift, swift architecture, swiftUI mvvm pattern 2021, model view view model, swift mvvm, mvvm swift tutoorial, swift 5 mvvm, swiftui mvvm
Id: ak8x-p-q8tU
Channel Id: undefined
Length: 14min 56sec (896 seconds)
Published: Tue Feb 02 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.