Swift: WebSocket Real-Time Data Introduction (2021, iOS, Xcode 13)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what is going on guys welcome back to the channel in today's video we're going to be learning about websockets a way where you can get real-time data from an api and this is something that backs apps like robinhood or any app that shows real-time data be it stock information or something else so before we get into it drop a like down below hit subscribe you guys know the spiel and let's dive into xcode so we're gonna go ahead and open up xcode we're gonna start by 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 web socket example let me go ahead and fix that typo there we're going to stick with storyboard and swift the ui is a little irrelevant here so this works with 50y as well go ahead and continue and save the project wherever you'd like i'll toss it onto my desktop now before we get into things let's go ahead and pick a simulator here we'll go with the 12 pro max i'm gonna jump into my view controller let me also expand my xcode window here and let's go ahead and just set a background color so we know our app is actually running so we'll go ahead and maybe make this system blue just like that hit command r to build and run and then we'll get into the weeds of the actual web socket implementation now this is something i've been playing around with personally a lot lately and it's really cool and it's really simple to set up so let's get into it so the nature of a websocket is you need to connect to it and continuously listen for messages in the receive function and you can also send messages so i'm going to stub out four functions that we're going to need to implement the first one is going to be ping the next one is going to be close which closes the web sockets the third one is going to be send and of course the last one is going to be receive now before we can actually implement these we need to actually create said web sockets so the way we go about doing this is we first need to create a session we want to create our own url session so we're going to say url session and we want to create this with a configuration delegate and a delegate queue so the configuration pretty simple we're not going to change anything we're just going to use defaults we need to supply a delegate and this is how we're going to get events like if the websocket connection was established if it was closed so on and so forth so we're going to go ahead and say self here it's going to yell at me because we haven't conformed to the delegate yet and the delegate queue we're just going to instantiate and pass in an operation cue you can also do this on the main thread or the main queue but ideally you don't want to do this on the same queue that you're doing your ui work on so we're just gonna pass in a new queue just like that now before this starts yelling at me it looks like it's already yelling at me let's come up here and conform to the url session and i believe it's called a web socket delegates and whoops let's try that one more time web socket delegates and the two delegate functions that we are going to bring in is i think it's called did connect or something along those lines let's see what's available we're going to say web sockets there is a websocket task here and we want the one for did close and did open there's actually two and we want both of them there so we're going to bring that in and we're going to bring in did close that is not what i want i think that's the right one let's double check it website a task did close now before we put anything in here let's go ahead and create the actual websocket so right now we have a session how do we actually get a websocket out of this so we're going to go ahead and say let's web sockets is going to be from this session go ahead and create a web socket task and we want to pass in a url here now how do we actually go about creating this url well we actually need a special websocket url and i've got my browser opened up here we're going to use this dummy test url that we can get data from and send data to i'll link this down below and right up here we're going to go ahead and create this url just like any other standard url we're going to pass this guy in as a string one thing that's interesting and important to note here websocket urls don't use the https protocol they use wss presumably for web socket stream so that's one differentiator here you can visually very easily just see so we're going to go ahead and pass that in i'm going to force unwrap because we know it's a valid url in your actual application you probably want to go ahead and unwrap it more safely now that we've got this websocket created we're going to say websocket.resume just like any type of url session task now one other thing i'm gonna do is i'm gonna create a global instance that we can hang on to for this websocket and the reason we're gonna do that is because we're gonna need a reference to this momentarily when we implement the other functions down below it's a web socket task we're gonna make it optional since uh by default it's not really assigned to anything we're gonna make this guy optional and let's actually give our app a run i'm gonna go ahead and print in here in the did open connection this is gonna get called as soon as we have opened a connection so we're gonna go ahead and say did connect to socket and then in the close here i'm also gonna go ahead and say did close connection with reason and notice there's a reason argument in the actual signature so we'll just print that out as well so let's go ahead and give this a run and the first thing that i screwed up is a typo so it looks like the reason is data so instead of i guess we could print it out but i actually had a typo there so we won't actually see something valuable unless we encode this to a string so i'm just going to get rid of that so we'll go ahead and give this a run build succeeded and we expect to see the connection successfully established down here uh did connect to socket so we're off to a good start now let's go ahead and implement the meat of the websocket which is actually sending and receiving uh messages uh and in your actual application i'm gonna stick a robin hood as the example if you were on a screen where you wanted to see real time you know price fluctuation you would send and receive market data so the first thing that you might be thinking what the heck is this ping thing so the nature of a websocket is you need to ping the websocket to establish a connection that the websocket is still alive so ping gets called every so often by the websocket to establish that hey the connection is still alive and it's really easy to implement this we're just going to say websocket if i can spell it correctly websocket and we're going to say i believe send ping just like that it has a callback and it gives us a error just like that are we going to say if let's error equals error we're just going to print it out so i'm going to say ping error just like that and we're gonna stick the error in there now this is a trailing uh closure so we can get rid of this i believe let's see if i can get away with this and get rid of that parentheses right there makes our code a little cleaner so that's ping for you now the next thing in here is closing the connection otherwise known as canceling it we're gonna call this by pressing a button on the ui that we'll add and this all we're gonna say is cancel now we can go ahead and cancel this uh with a actual uh reason or a status code here so we can go ahead and pass in going away an abnormal closure whatever the reason is and the reason is uh you know a data from a string that we can derive so i believe what we can go ahead and do is we can create a string and say data using utf-8 and we can go ahead and say demo ended now this is the reason you would send a reason is because the server might want to log on their side you know why was the connection closed was it an interruption or did something go wrong or did the user just navigate away so that's the other thing we want to do here send and receive this is for the actual data so for sending we're going to say web sockets i believe it is send and we are going to send a message so we want this one here we're going to send a string and what i'm going to go ahead and do in here is going to say send new message and i'm just going to put in a random integer since we're going to print this out so i want to have some variability in our console so it's going to be a random number one to a rather zero to one thousand now this completion handler here similar to the send ping will give us an error now if we had an error for any reason we shall print it out after unwrapping it so we're going to say if flood error is error we're going to say send error and we're going to stick that in there and then finally the last function that we need to implement is receive now you might be wondering why do we need to implement this shouldn't we continuously be receiving information the way that websockets work is we continuously will need to actually call this function receive to more or less ask the websocket if any new data came in so we'll we'll hook that up momentarily so we're going to say receive here notice there's an async awaits version of this too we're just going to use the one with the callback now this completion handler is going to give us a message and i believe an error as well and it's going to be wrapped inside this result so what we want to go ahead in here is do is switch the results if we got the success case we have a message now this message can be a data otherwise bytes or a string we'll take care of that in a moment but we're also going to get an error if something goes wrong so we're going to say receive error and we're going to stick that error in here otherwise in here we now want to switch on the message now if we get uh data we're going to handle said data in our case handle we're just going to print it out because we're being lazy so we're going to say data and we're going to interpolate the data in here maybe i'll say got data be a little more specific there next one that we're going to implement is string and this one is the one that we're going to see in our demo momentarily and once again we're going to simply print it out we're going to say got string and i'll stick the message in here and one last thing you're going to want to do is handle any other cases otherwise your compiler will complain at you so we're going to say unknown at default and i'll probably just break in here since we don't really need to print anything out and i believe that is all we need to do now we need to actually call these functions where the heck are we going to call them from well we're going to call them as soon as our connection is established so once we connect to our websocket we're first going to ping then we're going to send a message or maybe we'll receive a message first and then we'll send a message now the other thing you might be wondering is we're only calling the function all three of these once here so when do we go about actually continuously receiving data at the end of this receive function we're actually going to call receive again so we're going to say self dot receive we don't want to cause a memory leak so we're going to put a optional week capture here so we'll say week self just like that similarly for send we want to continuously send different messages for our example so what i'm going to do is we're going to send this message on the global queue after maybe one second so we'll say now plus one second we're gonna stick this guy in here self dots and we're gonna call self.send continuously every one second and i think that should do it hopefully i didn't miss anything and screw anything up so let's go ahead and give it a run and we expect to see a whole lot of stuff continuously printed out in our bottom console here so let's take a look at what we've got looks like we have some continuous things printing out so the first thing that we got here at the top is we connected then the server responded with this information here this info you are using a test api key now we're sending a message every single time with a random integer and the server just for this kind of test environment is sending the same message back so if we take a look at our code up here in our send function we're simply sending send new message with a random integer and then receive we continuously call that and the server is basically spitting that back out to us so that's websockets it's definitely working let's add a button to the ui so we can actually close this connection you never want to continue to keep a websocket open because that will be terrible for your app and you'll probably crash and we'll get a really bad reading in the app store so let's go ahead and add a close button here i'm going to add a close button we're going to create it like any other piece of ui programmatically we're gonna go ahead and instantiate a button in here like so return button i'm gonna go ahead and maybe we'll stick a background color in here just for the sake of uh seeing it more easily we'll say button set title we'll go ahead and make it close normal button set title color we'll make it black perhaps and this is for normal let's make this black not blue let's go ahead and stick this on our ui so i'm going to go ahead and say button.frame is cgrect 0 0 250 we should probably add it as a sub view and then finally let's stick a selector on this so we can actually have something happen and we're going to call this the close function we're just going to do like that and then this is going to be touch up inside let me fix my typo and this close function down here we need to prefix it at objc since it is a selector let's go ahead and give it a run and when i tap on that button hopefully it appears it'll close out our connection now it's at the top left because i forgot to center the button let me just go ahead and center it here really quick third time's a charm we should now see the button the dead center of our screen we got a connection established to our websocket we're gonna go ahead and click on this button and boom just like that it has cleared out our it has closed rather our connection now in our case we continue to get errors here when we try to send a message and the reason for that is uh because we continuously are calling that send function but the websocket is no longer open so we're getting an error here so what we should probably be doing is we should probably only be sending new messages in our demo if the error was uh you know nil but of course once again this is a demo you would have a more intelligent implementation of this if you were actually building your own app so that's websockets in a nutshell hopefully i didn't go through all this too quick it's really not a lot of code you've got your four core functions to ping close send and receive and then you leverage the web socket delegate to get your connection open and closed states and that's all there is to it let me know if you guys want to see more websocket examples in the comments down below i think it's something that's really interesting and honestly doesn't get covered a lot um irrespective to how cool it is drop a like down below if you haven't done so already hit subscribe if you're into ios swift tech want to stick around trying to get the channel to 50k maybe by end of year we'll see how that goes thanks again for watching i'll catch you on the next one
Info
Channel: iOS Academy
Views: 10,455
Rating: undefined out of 5
Keywords: swift websocket tutorial, swift, websocket, swift tutorial, swift web socket, swift url session, swift api call, url session swift, url session 2021, 2021 swift, swift tutorial 2021, swift for beginners, swift web socket 2021, web socket tutorial, swift POST call, wift basics, swift fundamentals, swift url session task, swift JSON, swift json tutorial, swift codable, swift 2021, swiftui, swift tutorial for beginner, how to make an app, swift programming, swift websockets
Id: VwzXiJgsDrE
Channel Id: undefined
Length: 16min 7sec (967 seconds)
Published: Wed Nov 10 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.