URLSession: JSON GET & POST Requests | Swift 3, Xcode 8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody my name is Kyle Lee aka kilo loco from kilo loco comm and today we are going to be going over URL session specifically a JSON get and post requests the tools that I'm going to be using today are Xcode eight point two point one and Swift three and I have marked this this tutorial to be at the beginner skill level because I'm going to be going over it's a pretty straightforward concept and I'm going to be going over over every line that I type in for you guys to understand what this tutorial will not be is how to parse the JSON that we get back I'm just going to be printing it to the logs but I do have a video if you want to know how to parse the JSON this is just more of how to access API and get the data into your environment moving forward with this tutorial you're just going to need to know the the Swift language basics and then just kind of have any idea of what callbacks and completion handlers are how they work just so that you can log that data and not be confused on what's happening so let's go ahead and get into it also I wanted to disclose this right away if you are looking for a specific tutorial this tutorial is going to be like I said JSON post and get a request this is not for multi-part form data so if that's what you're looking for I'll be doing a video on that next week so be on the lookout for that but this is just basic URL URL sessions just the simple stuff alright so let's go ahead and open up a new project I'm also not in my garage this time so my computer shouldn't stopping there shouldn't be in the interruptions in your video when you're watching this so I'm gonna call this URL session and then dude JSON requests and as always sorry for the dogs or the kids that you hear throughout this tutorial and we are going to put this right on the disk now we'll do it in kale learning actually because that's where I'm going to be doing my my source I don't even know what I'm saying I'm going to be putting this up on github so that's where this is going to be and this is where I put all my stuff so let's do it here like off my game today guys alright so the first thing I'm going to start off with is just the main storyboard just get two buttons going I'm going to be using buttons to do the different types of requests so let's get that going just two of them and this will be get and this will be post very simple very straightforward nothing fancy storyboards on stuck these are a little bit fancy right but other than that nothing nothing really fancy got a line on the center make them look pretty we want to space them out go out for 30 space in let's do 50 spacing yeah that's fine that's all we need all right let's clear this out connect them keep getting bigger fonts for you guys so that make sure that you can see everything that's going on and this is going to be in it is no nope not what I want to see it's trying to do the stack view make sure that I get the button so I'll do it from here instead and we want this to be in action so this is going to be on get get tapped and do the same thing over here on post tap right all set right there going back over viewcontroller and we're ready to go guys this is all we need to get going okay so we're going to start off with the get it's very easy very simple and very straightforward all we have to do is create a URL and you creating a URL it generally gives you an optional URL so what we'll do is we'll put in a guard statement card let URL equals URL and we're going to be making it from a string and else return all right so the actual URL I'm going to get I'm going to show you guys how to get there so let's bring up Safari that's my browser of choice and I'm going to go to Google and all you have to do to follow along is just do this or you can get the source code from github but all I'm going to do is type in JSON placeholder that's all I'm going to do this one right here it's going to be the fate of the first one at the top JSON placeholder comm typical comm under take on whatever you guys saw it you know I'm saying so all I'm going to do is I'm going to copy this the URL put it up in there and then we're actually going to be doing a get request so let's just go ahead and do users as you can see the different routes what they recommend so if you want to do a get request we could do any of these I'm just going to do this first one keep it simple well I wanted to do users let's do users keep it simple it's the same thing but now all right and then we just type in we just paste it right there this is all you have to do it really have to do is just get your API endpoint and you're done well not done but yeah so next what we're going to do is we have to create a session using URL session so let session equal URL session dot shared and then from this session what we're going to do is we're going to type in session dot data task oops let me go back over this I'm just so used to doing it so we're going to do data task and since what we can do is we want to do one of these ones with the completion Handler because we want to be able to be able to parse the data out and do whatever we want with it so as you can see right here you can do a data task with a URL or you can do a data test with the URL request all we need to do for your basic Gettler you don't need to pass in any parameters or anything like that you just hit your endpoint and it's going to give you the information that you want is just do the data test with URL just keeping it simple URL session is defaulted to get and you don't have to do any extra work so it automatically goes out and does a get request so we're going to type in URL and for the completion handler just go ahead and let me make this a little bit bigger so that we can get everything on one line we're going to go ahead and press ENTER and for data we'll just call this data for the URL response we'll just go ahead and call that response keeping it simple we can call it whatever we want it error we can call this you know poop if we wanted to call poop so um yeah and as you saw we have to also do optional changing chaining with these just to make sure that there is a there is a value inside them or else they can be nil so what we're going to do is we're going to do is data or actually let's get the response back because we want to make sure that the response was successful so the do if response or we have to do a flip I'm sorry like I said I'm off my game today if that response is equal to response then what we are going to do is we're going to print our response and it'll give us something that's fairly readable all the information that you're really going to need them that's all we have to do to see what the response was the other thing we're going to do is we're going to want to see the data and we could call this anything that we want we could call it potatoes and I don't know how to spell potatoes right now guys this is crazy I am so off I'm sorry let's just go back to data call this error like I said they could be called whatever you want and then optional chaining so if let data is equal to data then we're going to go ahead and do some stuff in here now we can't just print out data because what it will do will actually let me just print out that data for you so that you can see what's actually coming back and to finish this you actually have to call well you actually have to call dot resume if you do not call dot resume it will not call this task nothing will happen you'll just go through and nothing will happen also if you ended up doing something like this instead URL session whoa dot shared you um you and say let's say we did we wanted to do let session equal this right let's say you did something like that which is fine that looks a little bit uglier but notice that you can't do dot resume right here right so you can't do it right here so what you'll actually have to do is do such an dot resume down here so that's just a little heads up depending on whatever your coding style is I prefer to do it like this but that's just something that I ran into that I think would be helpful for you to know so there we go I think we're back to normal let's go ahead and run this I'd like to keep it on the S II and we should be able to see what happens it's going to pop up over here because this is full screen so yeah going back over it just getting the URL creating a URL session getting the data task with that URL I can go through check our response print the response if there's anything it's also going to go through check the data print the data if there's anything so one I press get and I go back over there let's see it didn't seem to work there we go so let's pull this bad boy out so this is the route this is the response so the top part all this jumble stuff up here this is all the response now you don't really need this but it's helpful for this part right here to check your status code and a status code of 200 is going to indicate that it was successful so 200 anything in between 200 and 300 200 to 299 exactly that's generally a good response if you got something like 400 then that means that that it was a bad call so you didn't do something right so if I go ahead and do this we're looking for Luers you know instead of users then I'm going to get a bad call and I'm going to get a 404 I'm sure that you get you have seen something like this on websites and web pages when you you know go to a weird spot in the and the website and you get like this 404 you know image saying website not found or page not found or something like that so that's usually what happens well not this exactly but that's it's exactly it's essentially the same thing when you type it in wrong you get that 404 missing page response so let's go ahead and put that back and also as you can see down here two bytes before it was like 5,000 something bytes like I said the data it's not going to come in as a readable format so we have to do it to put it into a readable format assuming that that whatever response that we have is coming back as JSON is that we actually have to convert this data into JSON data see five thousand six hundred and forty five bytes so what we're going to do as opposed to reading it in bytes because that doesn't help anybody is we're going to put this in a do try block so go ahead and do try and we are going to convert it to JSON so let JSON equal and this is a call that throw so we have to do try JSON serialization dot data and since we are reading we want to be able to read it we're not making it so we're not we're not writing it we want to read this that's how I remember it we're going to choose reading options right and we're with data we don't have an input stream so we're doing data so make sure you choose this one and then we're going to pass in our data as one would expect and we are actually just going to close this off right here we don't have to put anything you could put mutable containers that just lets you modify some of the actual JSON that came in but you hardly ever need to do that because you have to parse it anyway but ya just passed in this blank blank array or argument or whatever and that will give you your JSON so if we go ahead and try to print and it's giving me an error right now because I forgot to do the catch block down here Xcode can be kind of weird so let's just print that error the the standard error that's going to come from trying to do this and if we go ahead and run it and you know what I'm actually going to put this all on the same screen just make the screen a little bit bigger so that you guys can see everything happening on the same page and we don't need any of this over here all right where's my simulator right here all right so we're going to do the get response and bam we have our JSON look at that isn't it beautiful you it's still printing the data right here but this is the actual JSON that it's printing we can see that it's coming in as an array as an array and array of dictionaries because each of these are dictionaries and they all have the same format which is good JSON you have an array of dictionaries that are all formatted the same way so you can essentially parse through them properly I won't go through the parsing this is all you really need to know how to do it to access an API and then get the data back and that's what you get all right so it's it's very simple it's very simple it's very straightforward only a few lines of code most of it's just the do try block and the catch block and all that other stuff but everything else like this isn't necessary you don't need to check the response really it's just helpful if you don't know what's going on so yeah that's all you really have to do now the post post is a little bit different its overall the same but it but like I said it is a little bit different you have to do a couple more steps and let's go through that right now so we're going to start off the same I'm not going to make URL up there as a global variable I just want to go through everything from scratch so let's do all the same things guard let URL equal URL and we're doing it from a string once again and if we already know that we want this as our endpoint but we're not going to do the users because we're not posting users right so let's go back to our website and for a post request they say use posts with plural so just go ahead and copy that I coulda typed it in probably faster than I would have copied it but whatever that's what happens when you watch my tutorials is I do stuff that it's not really necessary all right anyway so remember how we did the data test with a URL this time with with post requests you have to do them with what's going on yeah excellent repeat you have to do them with URL requests you can't just do it with the URL because there's stuff that you have to put in the the request body and in order to do that you have to be able to access the request so let's make a request so let request equal URL request and everything is pretty named very simply for you guys we're just going to use this top one URL we don't need to go into cache policy or anything like that really this just gives you more control over your request like you could choose the cache policy like if you want to save certain things like if you know that they're going to be constantly real calling that API just to get the same thing the cache policy will make it easier for you as well as the the time the timeout interval interval I believe it's set to 60 cent seconds by standard maybe 30 seconds but you can change the timeout interval if you're expecting things to be either faster or slower but for this basic example we're just going to go ahead and go move forward with the URL so let's go ahead and pass in the URL right here and then as you can remember we're just going to make the session just like normal but we have to add a couple of things to our request so the first thing the first thing that we're going to want to do is actually we're going to want to we're going to want to add that it's a post request so go ahead and get your request and do HTTP method and we're going to set it to post that will let let the URL session know that we are doing a post request and then next what we have to do is usually we want to pass in some parameters so let's also do parameters what's going on here oh it's a variable I don't know why I did let usually when you do post I'm sorry I'm going jumping all over the place like I said I'm not on my game today I but usually when you do a post request you want to pass in some parameters so let's go ahead and set in some parameters so let's do let parameters usually these are you know dynamic you're going to want to get them from a field or something like that but I'm going to do a dictionary of per of parameters and keep it simple so let's say this was like Twitter or something you wanted to do a tweet right and you would normally have something like the the username right and it would be your username and then you would have your tweet and that would be like your message whatever you want to say like hello world hello world tweeting here so this would generally be like some type of parameters you can have as many as you want but they would generally be coming in as a dictionary you'd have like username would be set depending on whatever the API requires you to pass to it but you know the the actual value that you would put in here would come from something like your text field you would type in to your text field and you know put in kilo local maybe you have at sign before it or something like that so that's kind of the mentality that you'd be working with URL sessions in real life I'm not going to go into all that I just wanted to show how this is going to work next thing that we want to do is set the HTTP to something and what we're going to do is we're going to have to turn this these parameters into JSON so let me show you how that's going to work so let let our HTTP bodies call this whatever once again and we are going to do JSON serialization and this is going to be data and this time we're actually going to be writing it we have to create the JSON we have to turn this into JSON so we want to do the writing options right and we are going to pass in our parameters as you can see it's taking any so we're going to pass in our parameters and for this once again this could just be blank you don't really need it to be anything special but you'll notice that we're getting an error and that's because JSON serialization on the data it's a throwing function so what we have to do is we have to market with try and I'm not going to put in a do try block because we have to do another do try block later so I'm just going to do a guard right here and that's optional chaining we can keep it as a question mark in case it doesn't work and we still move forward with our HTTP body all right and now we want to set our HTTP body to the actual request body so HTTP body so let's go ahead and HTTP body is equal to our HTTP body which we can see is data all right so we're almost there guys now we actually want to make our session just like last time equal URL session and let's just stop this and get this stuff out of the way I don't like the way this looks hold on I like it to be a little bit more centered there we go URL session dot shared just like last time same old stuff session and we're still going to do a data task but this time instead of doing the URL like we did last time with the completion handler we're going to be using our request or URL request with a completion Handler and we're just going to pass in our request and we're just going to go ahead and press ENTER on this completion block and once again call it whatever you would like just going to go with the standard and we're going to print it out the same way that we did before write all this code is essentially going to be reproduced but I don't like to copy and paste if I don't have to it'd be easier because we're going to be doing the same exact thing but it's good it's good practice it helps in practice so if let response equal response then what we're going to do is print our response and that's going to give us that block to let us know like the status codes and things like that what kind of methods that we're calling and what's being sent and all that those types of things if let data equal data we're going to go ahead and remember we can't just print the data because it'll give us the bytes and we don't want the bytes we want something that's readable so we'll put it in this do try block because we have to do the JSON serialization and before Xcode blows up let's go ahead and print out our standard error that's going to be coming from our JSON serialization so let JSON equal try JSON serialization dot uh and this time once again we're not going to we're going to be reading this data not like before where we are writing the data we want to do the reading options oops wrong one I chose input stream but since width is the same we and it's just an overloaded thing we can just go ahead and pass in the data anyway and the reading options just leave one blank that's fine that'll work and then what we want to do is print our JSON all right so that's pretty much all we have to do just remember that when we do session with data test we always have to call da presume you got it bang all right so this is actually going to give us a weird result and I want you guys to see that because there's something there's a few things that I left out but this is the the very basics that you need to do a post request with a JSON that is so now we're going to do our post all right so we got a status code of 201 remember that anything in between 200 and 299 essentially means good that it worked and we got this so we have ID equals to 101 and if you're familiar with JSON that all you know that this does not look right see because if we try to parse this right you know it it just wouldn't work because we have ID which is a string and this technically looks like a strength but the there's a value to it you know so this is the key and this is the value so what's going on with that right so the reason for that is because we're sending up let's see where is it so right here in the HTTP body right we're sending up JSON and we're setting that as the body but the problem is is that the API does not know what it's trying to accept it just knows that it's getting this information it doesn't know if it's JSON if it's XML if it's just a bunch of strings it doesn't know what is coming into it so we actually have to let the we actually have to let the API know hey we're sending up JSON so in order for you to do that we have to go back into our request and we have to add one more line so requests and we're going to do add value and as you can see we're going to be putting a value right here for HTTP header fields so um these are our HTTP header fields down here as you can see not and we have to specify what kind of content type that we want to send to it so what we'll do is we're going to say we are going to be sending you again just to do application we're going to be sending you JSON right and the JSON is the application JSON is going to be set for the content type right so now since our request has added this value to the content type it will know that we're sending up JSON and let's see what happens when we when we run this again I purposely wanted to miss out on this step because what will happen is if you go through and try to implement this for yourself and you're sending it up to the API you're just not sure what's going on why things are coming back weird or something like that this will probably be your problem so now if we do the post and look at that beautiful JSON just as we would expected you know we have the ID is equal to 101 our tweet is equal to hello world just as we typed it username is also equal to @ kilo loco so that's all we really need to do guys for your post requests for your post requests um that's it it's very simple very straightforward there's no magic to it you don't necessarily need to use things like Alamo fire because you don't understand it this is all you really have to do just a couple of lines what is that 30 lines less I mean look at how simple it is how straightforward is URL sessions has become very easy to implement both get get is even smaller look at this 14 20 lines 20 lines really do it so it's really easy to use your own thinking you don't have to import a whole new bomb a whole new framework just to do your networking request there is some lack there's something lacking - URL sessions which is doing multi-part form data and like I said I didn't want to go over that today but I will be doing a video for you guys next week but if you wanted to do just something basic and get up and running with API and test out some of these awesome api's like let me just show you real quick there's awesome API is like there's a Pokemon API which you're probably really familiar with because awesome courses like dev slopes course goes over that but they go over it with the Alamo fire and there's kind of some mystery behind what's happening so now you can kind of go out and test using these api's sending these endpoints that they give you there's also a Star Wars API which I think is also really cool called swappi you get things like look at Luke Skywalker his his height his mass things really crazy awesome stuff so go out there and experiment with some of these api's and they all take JSON which is the amazing thing and you can just make some really cool apps parse this data throw it into a table view and that hey that's that's and that's right there for your portfolio so I'm going to go ahead and close this and last time I forgot to show you that I am going to be pushing this up to my github so I want to make sure I do that for you guys already made the repo for it but obviously there's nothing in it right now and this is just good practice just to show you guys if you don't really understand how to use use git so all we're going to do yours is obviously going to look extremely different from mine we're going to do is we're going to change directories into my desktop and then I call this one kilo loco learning or KL learning and then let's see what I have in here URL system JSON so I'm going to change the rectory into that and get a get clone no no no no no get what am I going I'm sorry in it and we are going to get remote add origin and paste that into there and get pull origin master and type in my password and we're going to add them all URL session get and post requests requests and let me specify JSON because once again multi-part form data is different git push origin master alright so whenever you watch this video if you just want to see how I implemented the code it'll be up here at this at this URL and the link will be in the in the description so you have full access for that alright guys I hope that this cut this tutorial was informative I try to go over it for beginners this is very straightforward topic so I would only imagine that somebody that doesn't really have experience with URL sessions is probably watching this tutorial which is why I broke it down so in-depth and even some of the easier things I wanted to go over in detail just try to be as thorough as possible but yeah once again my name is Kyle Lee aka kilo loco from killa loco calm and feel free to reach out to me if you want to see any tutorials on any specific subjects in Swift I would love to do that also if you live in the LA area I am going to be hosting meetups more regularly you can look for my actual meetup group let's go over to that right now it's called applied swift foothills right here you go ahead and join my meet-up i'm going to be start going to be scheduling meetups more often so if you want to join us for applied Swift it's going to be about all things Swift and it's going to be project-based so whenever we do meetups we're going to be building a project that we could essentially you know get up and running and hopefully you can make it a little bit prettier on your own time and then make it part of your portfolio maybe upload it to the App Store well yeah you can join here if you're interested in that you can tweet me on twitter at kilo Loco kilo underscore logo and yeah just keep in touch and thank you for watching the video and as always code passionately guys alright
Info
Channel: Kilo Loco
Views: 80,591
Rating: undefined out of 5
Keywords: swift urlsession, swift 3 urlsession, swift get request, swift post request, swift json request, swift json get request, swift json post request, swift json networking, swift networking, swift json serialization, ios networking, swift alamofire networking, swift alamofire, swift api call, swift get data, swift post data, how to call an api in swift, how to use urlsession, swift nsurlsession, swift networking for beginners, swift api for beginners, swift json for beginners
Id: aTj0ZLha1zE
Channel Id: undefined
Length: 37min 31sec (2251 seconds)
Published: Sun Apr 23 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.