Explore how to implement the networking/weather data access layer first.
- [Instructor] So let's start defining our network access layer. First, I create a new group, I call it Networking. Then, I add the new Swift file. New file, Swift. I call it NetworkController. Let's remove the header, we don't need it. Now, instead of creating a base class, I start by defining a protocol. Let's call it NetworkController.
I make it public so that it can be accessed from everywhere else, and call it NetworkController. We need a method for fetching the weather information. Let's call it fetchCurrentWeatherData. The method needs at least one parameter, the name of the city, which is of type string. The method should return a meaningful set of data, which describes the weather. Let's call it weatherData.
I'm going to make the return value optional. We may not always be able to return valid information since we're relying on networking. The method takes a single argument, the name of the city, and returns this weather data instance, but we haven't defined the weather data type yet. We're typically interested in the temperature and the current weather conditions, so I'm going to create a public structure, which holds all this information.
First, we need a temperature property of type float. Then I declare a property called condition of type string. This will provide a short description for the weather, like for example, clear, rainy and so on. Also, the temperature unit may vary, so we should add this information too, and I make it of type TemperatureUnit, which is also unknown at this point.
TemperatureUnit should be an enumeration. I'm going to define three TemperatureUnits, but first, I need to make it public as well. It's of type string, as it is going to hold strings, and inside, it has three cases: scientific, metric, and imperial.
Now, we have the basic types, let's get back to the fetchCurrentWeatherData method. The method fetches data from the Internet. This means that it won't return instantly. The response times may vary depending on various factors, like the network speed, server load, and so on. Such long-running tasks should be implemented as asynchronous methods. We should always avoid blocking the app for an indefinite amount of time. An asynchronous method doesn't block the caller's thread.
After invoking the method, the execution on the calling side continues instantly. Swift provides an easy way to implement asynchronous methods. Instead of using a return value, we can use a completion handler. Now we have the basic types.
- Comparing object-oriented programming with protocol-oriented programming
- Methods and class-bound protocols
- Adopting a protocol
- Declaring asynchronous behavior
- Preparing and implementing fallback logic
- Implementing an app using protocol-oriented programming