iOS Dev 33: MVC Design Pattern Explained with Example | Swift 5, XCode 13

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey guys welcome back to my channel for those of you who are new my name is manuel and um if this is not your first time in my channel and you haven't subscribed then maybe just consider clicking the subscribe button um you have a lot to learn right so in today's video we're going to be learning about the mvc design pattern and this is actually something that many of us have consciously or unconsciously worked with all right so we're going to be doing today is i'm basically going to explain how things are working just so that um the next time you are writing code you are more deliberate right you understand exactly what is happening okay so um yeah let's get to it so what is mvc let's start with m so m means model and model you can think of as your your data layer so basically it gives us the structure of our data so for example we have our user model and the user model has like first name last name email phone number etc right so uh that's what basically what the model is now um in swift or in ios we are able to create models using either a struct or a class so you have like struct and then the model name then you open your curly braces and then pass in like your attributes and your functions right so uh the next thing we have is our view and just like as the name implies uh it's basically what we can see on our device so um you run an application you can see your buttons you can see your text fields you can see uh whatever controls we have on the screen so that's basically what the view is and finally we have the controller as the name implies again it's responsible for controlling things um that are happening within your app so basically it serves as a sort of middleman between the view and your model right so um a view performs a particular triggers a particular event the controller listens to that and then it handles it depending on whether or not it needs data from the model it goes to the model retrieves that data and then updates the ui if it needs to just update the model then it gets some data from the ui and then goes to the model and updates the model right so the controller basically is the one in charge of just making sure that things are connected end to end all right so uh let's actually see the flow in action so first of all we have the view just like we said so um a user performs a particular action so maybe like a button click or a like the user's typing some text in the field and um if let's say for example we want to listen to whenever a field text is entered in the text field we want to change the color of the ui view for example so the controller listens to that listens to the event or the user action and then checks whether or not the text meets a particular criteria and if it does it just goes ahead and updates the view in our case updates the background color all right then alternatively if the user action requires some data from the model then the controller just goes to the model and updates the model if he needs to update but if he needs to retrieve it just gets the data from the model and then the controller is notified whenever it is done and then the controller just goes ahead and updates the view so that's like the general description of the flow throughout the entire mvc design pattern all right so the next thing we're going to do is now we're going to go into code just so that i can show you practically what happens um in an mvc system okay so what we're going to do is we're going to open up xcode and actually have a starter project created just so that i don't waste much time implementing the design for this explanation right so if you go over and actually i have a link to this particular project in the description so if you want to follow along then just go ahead and pause the video download the starter project and you're going to have this exact code that i currently have and then we can go from there all right so basically just to walk walk through what we currently have if you open up the main.storyboard we have two view controllers over here the first one is um a login screen okay and the second one is sort of like uh well this is a home view controller and the idea of this is when your login is successful then it takes you to the successful screen all right so that's basically what what this application currently does and if you go over to the login view controller you can see that nothing is happening here we have references to the email and password fields then we have a reference to our login button click so whenever you click the login button this particular function is is triggered then this basically is so that when you click on the body of the view it resigns the keyboard all right then if you go over to the home view controller there's nothing happening over here is just in boilerplate code all right good so now in ui kit we have um our view and our controller combined into a single file which is called the view controller all right now don't be um confused about that um since if you are working with uh storyboards for example you can basically just think of your actual design as your view so just like we explained the view is whatever design the user sees so our buttons our labels our text field so you can think of this as your actual view all right then you can think of your login view controller as your controller because this is where all of the logic for how your view is going to be updated on how data is going to be gotten is going to be present right so you can think of this file as your controller it basically controls the flow of your application all right now if you are working if you are building programmatically then it is very possible for you to basically separate them into individual files so you can create your view as a view so i could have something like login view then i would have something another one like login controller all right now in the login view all i'll be doing over there is to design my buttons so um since i'm not doing like a drag and drop using the storyboard i'll now go ahead and say something like uh let email field be equal to ui text field like this and just go ahead and style all right then add my constraints and positioning and all those things so this can be done in your login view then in your controller you can now do the actual logic all right so it just depends on how you feel like structuring your code base but since we're working with storyboards then we're just going to use it like this so the login view controller is where our view logic is going to be and we're going to think of our main.storyboard as our view and then the next thing we're going to do is we're going to create a model and just like many of us are already aware if you want to create a model just open create a new swift file we're going to create a user model because what we're trying to simulate is you log in and a user object is created okay so um we're going to create a user model and we're going to make this a struct so struct user and we're just going to create a couple of um attributes over here i'm going to have first name as string and um let's add last name email let me see age if i want to do that and let's just stop over here but as you know we can have like a whole lot more we can have things like address we can have location we can have nested um models so an example would be let's say i wanted to do location um i'd now say struct location like this and say what's um lot if i wanted to do like coordinates or something then lng i'm just writing rubbish it's a double and this will be double like this so location is going to be of type location all right so this is a nested model right in the nested struct if you will so yeah you can do this okay so um good so this is our model again just to go over it again we have our view and our main dot storyboard our view like this like this then we have our controllers the login view controller we have a home view controller cool then we have our model which is our user model all right so what we want to do now is the first thing we're going to do is we want to listen to changes so let me just go ahead and quickly run this application just so we see what we currently have good now if you look at this you notice that when i click on this login button or actually it's just enabled so what we want to do is we don't want this button to be enabled unless there's text and uh both the email and the password all right so we only want this button to be enabled when both of these guys have at least a text right so what we're gonna do is we're going to head over to the login view controller and what we're going to do here is we're going to create a new function so private func and we're going to call this validate fields all right and we're going to make this or before then let's just hold on so now we're going to add listeners to both the email and the password fields so how do we do that i would just say email field.addtarget and the target is going to be self action is going to be hash selector and self dot validate field then the control is going to be editing um editing changed wonderful so um whenever the value of the textview changes is going to trigger this function and we're going to have to add at objc right here to fix this error okay so um whenever the value of the email field changes is going to trigger this function to to execute we're going to do the same thing for the second field which is the password field all right now what we want to do here is we want to check uh we want to set the button to be enabled or not so we need to create a reference to that button so just go over to the main.storyboard and all these things i'm doing here should be quite familiar to you i'm hoping so hold down control click drag bring this guy over here this is going to be the login button then we go back here and here we can say login button is enabled to be equal to so it's going to be enabled if email field dot text is not equal to this and password field.text is not equal to this and guys this is a very simple and basic validation so you can of course make it more complex because you know you can verify that email is email all right so i'm just trying to keep things simple so this is going to validate the field and update the um the button to make it either enabled or not so uh let's actually just go ahead and run this and um actually before we do that we want the default state of the button to be oops i don't need this so we want the default state to be disabled right so we're gonna click on the button just close this and bring this guy up so go to the attributes and of course you can do this by code but just come over here and click enable right and you can see that it actually gave us like a visual representation that it's not clickable all right so um what we're gonna do is we're gonna run this and let's see what we currently have all right so you can see that it is currently not enabled and we can't click it so i'm going to add some text here and i'm going to add some text here you can see that it automatically just became enabled so what was happening if we were to go through the mvc flow again is while we were typing right while we were typing the view was notifying the controller right so while it was notifying the controller the controller was performing some logic and based on the logic the controller saw that it needed to update the ui and it updated the ui automatically all right so that's the mvc flow now when we click on the login button what we want to do is we want this login button to simulate a network request so um we're going to have like a network service that is going to check the values in the email and password fields and if it is a certain value we want to go to the login screen or the logged in screen the home screen so how do we do that let's just go ahead and create a very quick network service so we're going to say network service like this and here we're going to click create a class called network service service and we're going to create a static let shared just to make it a singleton i don't think i've made a video on singleton yet but i'm sure you guys have already learned because of the way we use it but if you like have questions about this then just let me know and i'm gonna make a video on that in it great so now we're going to create a function over here called login and this is going to take in two parameters the first one is the email and the second is password all right close this i'm going to add a completion handler over here just so that we know that it is just to simulate that it is logging in so we're going to say um completion and this is going to be at escaping and we're going to just pass symbol just so we know whether or not it is successful and void all right so next what we're going to say here is dispatch q dot global so we're going to jump off the main thread and we're going to execute this code so we're going to say wait for like let's say two seconds and um when we're done we're gonna say did i miss an argument nope oh no no not wait sleep so sleep for two seconds and where you're done um we're gonna jump back to the main thread and say dispatch cue.main the sync and uh what we're gonna do here is we're gonna call the completion and we're going to pass in some value but before we do that we're going to do a check so we're going to say if email is equal to test test.com and password is equal to password the most secure password in the world then we're going to call completion and pass in true otherwise we're going to call them completion and pass and false then at the same time we're gonna have a private and this is basically gonna simulate i wonder what i'm typing so this is basically gonna simulate um like our local storage all right so rather than making network requests want to just create a user when we log in so this is going to be user and this user is going to be our model right so we have a user model which is going to be what this user is and it's optional because you know if you're not logged in then it should be no all right so now that the login was successful um what we're going to do here is we're just going to say um user should be equal to user and we're gonna have to pass in all of these values so first name is going to be emanuel last name acquire email test test.com a just gonna be 24 location is a nested one uh we're just gonna do one point this i'm just putting some random random values over here minus six dots good so this is our user object and it's gonna set it like this otherwise we're just going to say user equals now all right so this is very straightforward we're just creating a very simple mock um network request all right so uh what did i miss oh yeah yeah because we're accessing it uh within this uh dispatch q block and actually i have a video talking about um memory leakages i think so uh something you're going to need to or you want to research just so you know how to make sure that you don't have strong references to a particular object all right so i'm going to leave a link to that in the card right at the top great so now we have our login method implemented so how do we use this in our view model view controller rather what we're going to do is whenever you click on the login button because remember the only way this is going to trigger is if the button is clicked and the only way the button is going to be clicked is if the button is enabled so it's safe for us to simply say network service dot shared dot login and the email we're going to email field.text and i'm just gonna force this because i'm sure it exists all right but it's always good to be safe so don't don't do this so passwordfield.txt and we're going to force this as well then the completion is just going to have success so here if success so if the login was successful what we want to do is we're going to say um go to the next view controller so how do we do that i'll just say that controller be equal to storyboard or let's actually move this to a different function so private func go to home page all right so let controller be equal to storyboard done instant share view controller with identifier and actually have the identifier already set as uh home view controller so yeah we're just gonna oops copy that paste that over here and then we're gonna say um present and we're going to be presenting the controller we're going to animate this and the completion is of course going to be new so now let's go ahead and try this so here i'm just going to say go to home page else for now we're just going to use a simple print statement to keep things simple oh shoot so um invalid credentials good so let's go ahead and run this and let's see what we currently have before i go ahead and explain this so yeah this has to be self great so um it's not enabled so we click nothing happens i write some wrong email on password i click login we should see after two seconds remember two seconds delay even though we don't have a loader over here so i click on it again i've clicked one two and we get like that so two zip so now let's go ahead and put the correct value so test at test.com and the password is password login and after two seconds voila great so what we're going to do next is when we open up this page what we want to do is we want the controller to access our model and get us the name of the basically the full name of the user that is logged in all right so when we get that name we want to display that in this welcome label so how do we do that first of all we're going to go back to our network service to simulate a get request so we're going to say func get logged in user and uh this is basically going to return a user because we're simulating that we're getting this from the device not from a network request because this user is currently logged in so uh what we're going to simply do here is return user because user is the user that was created over here okay so this is gonna get that user and now we can go to our home did i miss something okay so this is optional so i'm just gonna add optional like this or yeah let's let's just add optional like this you could actually just force it because i'm sure that the user is there so i could do this all right so whichever one suits you um so we're going to go over to the home view controller and we're going to go over the flow again for the mvc architecture or can you already think of how the flow works so um basically what is going to happen is the view is loaded right the view now the view did load is going to is where we're going to fetch our user data so the controller is going to say okay i need to get the user data and i'm going to get this from the model right so it's gonna use the network service to access our our model and retrieve the logged in user and when it has that the controller again is going to update our ui and basically just set the first and last name all right so um how do we do that very simple right now if you do load we're going to say network service dot shared dot get logged in user and this is going to return a user object so you can come over here and just say user to be user like this we're sure it's going to exist so here we're going to say user equals this all right so this is going to pass in the user so now you can of course create a private function over here and say populate user name or welcome user or something like that so welcome user and basically what this function is going to do is say um welcome label dot text should be equal to hello and we're going to pass in the user.firstname and here we're going to say user dot last name awesome so here after getting the user we're just going to say welcome user wonderful so now we're gonna run this application and what we expect is when uh when we enter the valid credentials by saying um testattest.com and password when we log in we should see hello and emmanuel acquire and that's just the way mvc works this i like i said before it's something that you've definitely worked with and if you haven't actually developed any kind of applications in the past i have a video a series actually where we created a food ordering application using the mvc and basically this is how things worked so it's very straightforward just to go over it one more time we have our model which basically represents our data so um yeah then we have our view which is basically what we can see on the screen and we have the controller which basically connects both of them it performs a logic for the view so updates the view as it should and if it needs to get data or update data in the model it just does that by itself so the controller is like the middleman that's just arranging everything right now um mvc is very good it's very fast um and it's best for like simple projects that don't have like a lot of things happening all right but as your project becomes larger then mvc is going to become sort of messy right it could become so large you're going to be having like you'll be doing a lot of things in your view controller like if you see over here we're doing our network call and our view controller our view control is directly accessing our um like our model and has access to everything in our model so all of these things can become uh quite messy and a little bit difficult for us to manage our code base so um there's a solution for that there's another design pattern that basically makes things a little more smooth and that's the mvvm design pattern and we're gonna be covering that in our next video so um if this is something you're interested in learning then subscribe turn on the post notification and you're gonna be aware immediately i release the next video so if you have confusions or questions about the mvc feel free to leave it in the comment section i'll definitely respond and until then have an amazing rest of your day bye
Info
Channel: Emmanuel Okwara
Views: 261
Rating: undefined out of 5
Keywords:
Id: sbYaWJEAYIY
Channel Id: undefined
Length: 27min 41sec (1661 seconds)
Published: Sat Dec 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.