Unlimited WordPress themes, graphics, videos & courses! Unlimited asset downloads! From $16.50/m
Swift 1
  • Overview
  • Transcript

3.1 Sessions and Configurations

In this lesson, we’ll start coding for the network by looking at the concept of network sessions, and how to use URLSessionConfiguration to set up a network session with sane defaults.

Related Links

3.1 Sessions and Configurations

Hi and welcome back to Go Further with Swift where we build a better app for iOS. In this lesson we start with the networking part of the course by creating a session and task to fetch some data. We are going to use the data from OpenWeatherMap which provides current weather data around the world. To use the API you need to subscribe, which is completely free and generate your own API key. To separate the business logic and networking from the user interface I'm going to create a new class called Weather API. It follows the shared instance pattern, having a static shared property with an instance of the class and a private initializer. To be able to adapt the URL easily, I'm going to put it into a global property called wetherURL. The free plan of the API doesn't support SSL encryption so we're using HTTP here. I'm using the latitude and longitude and point of the API since this is what we get from quad location. To provide the necessary parameters, I chose string replacement as the way to go since it's easy to do and can't cause any problems with the data format we have. To use the API we need an app ID that contains the API key. Finally, we need to set some units, so we don't get the temperature in Kelvin. You can choose Metric or Imperial here. I'm going to paste my API key to the source code but I will roll it after recording the course, so please create your own. Now that we have prepared everything, let's start with some networking. Even if you're doing multiple requests you probably want to have a shared session in your API client. This configures things like caching, default headers, and so on. If you don't care about configuration much, you can use the shared URL session provided with foundation. So why don't we fetch some data very quickly now? You can do this with a task. There are three types of tasks, data task, upload task, and download task. The difference between data and download task is that the first one is storing the result of the request in memory, and the latter one stores it on disc and provides you with a file URL. This is very useful if you want to store larger files like photos or videos that you've downloaded. To be able to make a request, we first need to fabricate the URL. I'm creating a helper function for that, that does the string replacement and creates the URL object. It takes latitude and longitude as parameters. First we take the beta URL and replace all occurences of API key with curly braces and fill our API key. Then we also substitute the latitude and longitude respectively of the parameters provided in the function. Finally we have to create and return the URL. I'm going to forcefully unwrap it here as I know that I've a valid one, and I'm saving a few NULL drives down the road. In a real app, you shouldn't do that. So let's use the URL and the data task and fill in some latitude and longitude that roughly maps to my area. Since network requests are asynchronous, the data task has a callback clock and receives the data, responds an error object. We are going to talk about this more in the next lesson, but let me just create a guard clause to ensure we have data and then print it. I'm going to add the call to the shared weather API, and viewed it loaded in our view controller, so it gets initialized and makes the request. Except it doesn't. To understand why, I have to explain the different states of a task. A task can be suspended which is the status of the task after it gets created. To start it, you have to call Resume. A task can also be running. There you can either call cancel which finishes the task permanently or suspend it. A download task that gets suspended can resume later on from the position it stopped. The final state of the task is done where it has finished the request. Now the task is trying to run but iOS blocked the request. With the introduction of app Transport Security, Apple requires you to make encrypted network connections and blocks others by default. Of course it isn't always possible to make an encrypted request. So you can define exceptions, which is what we have to do. In the info.plist file find the app Transfer Security settings and add Exception Domains there. Here I'm going to add api.openweathermap.org as a key, being as restrictive as possible. Within the domain name dictionary, I need to allow NSExceptionAllowsInsecureHTTPLoads as a Boolean, and set it to Yes. This allows us to make the request. Let's build and run, and you can see we have 490 bytes of data. Since I want to inspect the contents, I can convert it to a string. Now you can see the JSON response string. It contains the weather data like light rain, the temperature of three degrees Celsius and the city name. Apparently I didn't quite hit Vienna but some city in Chechnya. So we made a successful request. Now let's talk about configuration. There is a URL session configuration class that defines the settings for your session. There are three possible configurations to start from. Default is the one you most often want to use. It contains settings about caching and headers. Ephemeral has the same, but it's a setting for privacy sensitive connections since nothing gets stored on disk but everything is kept in memory. And the background session is good for downloading videos or photos and as it says, the background. There are a few settings I want to point out like additional HTTP headers where you could set the authorization header for an authenticated session. Another one is Network Service type. If you have an important connection like a voice call, you want iOS to prioritize its traffic to avoid cutouts. So you can specify that here. Your cache policy is an important setting as well, since it determines if the task uses cached data, or always reloads it from the network. When you are done configuring, you can set the configuration on the session. Every change you make afterwards gets ignored with this session. You have to set it before setting the configuration on your URL session intializer, like allowing or forbidding cellular access. We have made our first successful request to an external API, and also learned how to configure on that web session appropriately. In the next lesson, we are going to use a proper request object, and also look at the response in more detail. See you there.

Back to the top